以后出现的所有重复项(在本例中按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 onorder 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获取记录集中的第一条记录。

10-06 08:43