以后出现的所有重复项(在本例中按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
中执行? 最佳答案
必须使用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
从PostgreSQL documentation:
DISTINCT ON表达式必须与最左边的ORDER BY匹配
表达式。ORDER BY子句通常包含
表达式,用于确定
组上的每个不同项
因此
distinct on
将使用按id, rational
排序的记录集,并为每个id
获取记录集中的第一条记录。