如何删除 Postgres 中的两行重复数据之一?
How do I delete one of my two duplicate rows of data in Postgres?
我正在使用 Postgres 9.5。我有以下查询,旨在在我的 table.
中查找相同的数据行(但 ID 唯一)
select e.name,
e.day,
e.distance,
e.created_at,
e2.created_at
from events e,
events e2
where e.name = e2.name
and e.distance = e2.distance
and e.day = e2.day
and e.web_crawler_id = e2.web_crawler_id
and e.id <> e2.id
and e.web_crawler_id = 1
order by e.day desc;
我最终想删除其中一个重复的行——所以也许删除具有最大“created_at”日期的行。但是我不确定如何只对两个相同行中的一个 return 编写查询。我该怎么做?
您可以使用 LIMIT:
select e.name, e.day, e.distance, e.created_at, e2.created_at from events e, events e2 where e.name = e2.name and e.distance = e2.distance and e.day = e2.day and e.web_crawler_id = e2.web_crawler_id and e.id <> e2.id and e.web_crawler_id = 1 order by e.day desc LIMIT 1;
有很多方法,但无需改变您的 sql 太多,您可以做更多而不是 <> for id:
select e.name, e.day, e.distance, e.created_at, e2.created_at
from events e, events e2
where e.name = e2.name
and e.distance = e2.distance
and e.day = e2.day
and e.web_crawler_id = e2.web_crawler_id
and e.id > e2.id
and e.web_crawler_id = 1
我正在使用 Postgres 9.5。我有以下查询,旨在在我的 table.
中查找相同的数据行(但 ID 唯一)select e.name,
e.day,
e.distance,
e.created_at,
e2.created_at
from events e,
events e2
where e.name = e2.name
and e.distance = e2.distance
and e.day = e2.day
and e.web_crawler_id = e2.web_crawler_id
and e.id <> e2.id
and e.web_crawler_id = 1
order by e.day desc;
我最终想删除其中一个重复的行——所以也许删除具有最大“created_at”日期的行。但是我不确定如何只对两个相同行中的一个 return 编写查询。我该怎么做?
您可以使用 LIMIT:
select e.name, e.day, e.distance, e.created_at, e2.created_at from events e, events e2 where e.name = e2.name and e.distance = e2.distance and e.day = e2.day and e.web_crawler_id = e2.web_crawler_id and e.id <> e2.id and e.web_crawler_id = 1 order by e.day desc LIMIT 1;
有很多方法,但无需改变您的 sql 太多,您可以做更多而不是 <> for id:
select e.name, e.day, e.distance, e.created_at, e2.created_at
from events e, events e2
where e.name = e2.name
and e.distance = e2.distance
and e.day = e2.day
and e.web_crawler_id = e2.web_crawler_id
and e.id > e2.id
and e.web_crawler_id = 1