应删除稍后出现的所有重复项(在此情况下由rational
排序)。但是以下查询不起作用:
SELECT DISTINCT ON(postcards.id) postcards.id, postcards.title, rational
FROM
(
SELECT postcards.id, postcards.title,
some_complex_condition as rational
FROM postcards
ORDER BY rational
) as postcards
我希望它取决于订购,但事实并非如此。似乎需要在DISTINCT ON
上设置一些优先级。可以在Postgresql
吗?
答案 0 :(得分:3)
您必须使用distinct on
中order by
内的列。
select distinct on (postcards.id)
postcards.id, postcards.title, rational
from
(
select
postcards.id, postcards.title,
some_complex_condition as rational
from postcards
) as postcards
order by postcards.id, rational
DISTINCT ON表达式必须与最左边的ORDER BY匹配 表达式(多个)。 ORDER BY子句通常包含其他内容 表达式,用于确定所需行的优先级 每个DISTINCT ON组
因此distinct on
将使用id, rational
排序的记录集,并为记录集中的每个id
创建第一条记录。