2

以后出现的所有重复项(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吗?

4

1 回答 1

4

distinct on您必须在in 中使用列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 文档

DISTINCT ON 表达式必须匹配最左边的 ORDER BY 表达式。ORDER BY 子句通常包含其他表达式,这些表达式确定每个 DISTINCT ON 组中行的所需优先级

因此,distinct on将使用按顺序排列的记录集,id, rational并为每个记录集中获取第一条记录id

于 2013-09-01T15:56:23.770 回答