如何从PostgreSQL(8.4.20)获取唯一行,此时我的查询如下:
SELECT
DISTINCT ON(student.id) student.id,
student.*,
programme_stage.*
FROM
person AS student
INNER JOIN
programme ON (student.id = programme.person_id)
RIGHT JOIN
programme_stage ON (programme.id = programme_stage.programme_id)
ORDER BY
student.id,
student.last_name ASC,
student.first_name ASC
LIMIT 10 OFFSET 0
上面的查询工作正常,但我想按第一顺序排序最后一个名字。
示例数据:
| id | first_name | last_name | programme_id | programme_stage _id |
|----|------------|-----------|--------------|---------------------|
| 1 | Michał | Nowak | 1 | 1 |
| 2 | Jan | Kowalski | 2 | 2 |
| 3 | Tomasz | Thomas | 2 | 1 |
预期产出:
| id | first_name | last_name | programme_id | programme_stage _id |
|----|------------|-----------|--------------|---------------------|
| 2 | Jan | Kowalski | 2 | 2 |
| 1 | Michał | Nowak | 1 | 1 |
| 3 | Tomasz | Thomas | 2 | 1 |
如果我尝试从订单状态student.id列中删除,我收到错误:
..SELECT DISTINCT ON expressions must match the expressions .. ORDER BY LINE 2: DISTINCT ON(student_person.id) student_person.id,
^
答案 0 :(得分:1)
使用子查询:
SELECT s.*
FROM (SELECT DISTINCT ON (s.id) s.*, ps.*
FROM programme_stage ps LEFT JOIN
programme p
ON programme.id = ps.programme_id LEFT JOIN
person s
ON s.id = p.person_id)
ORDER BY s.id
LIMIT 10 OFFSET 0
) s
ORDER BY s.last_name ASC, s.first_name ASC;
注意:
LEFT JOIN
到RIGHT JOIN
。但是,因为您使用person
表进行聚合,所以您可能需要内部联接。id
两次。*
。