我正在使用Postgres 9.5。我有以下查询,旨在查找我的表中相同的数据行(但唯一的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”日期的行。但我不确定如何编写查询只返回两个相同的行之一。我该怎么做?
答案 0 :(得分:0)
您可以使用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;
答案 1 :(得分:0)
有很多方法但是没有更改你的sql,你可以做的比做而不是&lt;&gt;对于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