PostgreSQL-SELECT DISTINCT,ORDER BY表达式必须出现在选择列表中

时间:2018-07-09 19:33:03

标签: sql postgresql

我是SQL的新手。

我想我误解了如何使用DISTINCT关键字的概念。

这是我的代码:

SELECT DISTINCT(e.id), e.text, e.priority, CAST(e.order_number AS integer), s.name AS source, e.modified_time, e.creation_time, (SELECT string_agg(DISTINCT text, '|') FROM definitions WHERE entry_id = d.entry_id) AS definitions 
FROM entries AS e
LEFT JOIN definitions d ON d.entry_id = e.id
INNER JOIN sources s ON e.source_id = s.id
WHERE vocabulary_id = 22
ORDER BY e.order_number

错误如下:

ERROR:  for SELECT DISTINCT, ORDER BY expressions must appear in select list
LINE 6:  ORDER BY e.order_number

只是试图了解我的SELECT语句的样子。

2 个答案:

答案 0 :(得分:1)

在我看来,您正在尝试在单个列而不是其他列上进行区分-这肯定会失败。

例如,select distinct a,b,c from x返回a,b和c的唯一组合,而不是唯一的a,而是正常的b和c

答案 1 :(得分:1)

如果您希望每个不同的e.id行,那么您正在寻找distinct on。使order bydistinct on键保持一致非常重要:

SELECT DISTINCT ON (e.id), e.id, e.text, e.priority, CAST(e.order_number AS integer),
       s.name AS source, e.modified_time, e.creation_time,
       (SELECT string_agg(DISTINCT d2.text, '|') FROM definitions d2 WHERE d2.entry_id = d.entry_id) AS definitions 
FROM entries e LEFT JOIN
     definitions d
     ON d.entry_id = e.id INNER JOIN
     sources s
     ON e.source_id = s.id
WHERE vocabulary_id = 22
ORDER BY e.id, e.order_number;

鉴于子查询,我怀疑有更好的方法编写查询。如果有兴趣,请提出另一个问题,提供示例数据,所需结果以及逻辑描述。