Postgresql优先级不同

时间:2013-09-01 15:54:25

标签: sql postgresql distinct

应删除稍后出现的所有重复项(在此情况下由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吗?

1 个答案:

答案 0 :(得分:3)

您必须使用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组

因此distinct on将使用id, rational排序的记录集,并为记录集中的每个id创建第一条记录。