2013-09-01 101 views
1

應刪除稍後出現的所有重複項(在此情況下排序爲rational)。但以下查詢不起作用:Postgresql不同於優先級

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 ONPostgresql可以嗎?

回答

2

您必須使用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子句通常含有附加 表達式(s)表示,確定行的期望優先級內 ON組

所以distinct on將使用記錄命令通過id, rational並採取第一記錄中記錄的每個id每個不同。

+0

非常感謝! – tiktak