首页 > 解决方案 > PostgreSQL:如何对未包含列的联合查询进行排序?

问题描述

我尝试ORDER2 UNIONed 查询。运行这个:

SELECT b.id
  FROM book.book b 
    WHERE title ILIKE '%something%' 
UNION
SELECT b.id
  FROM book.book b
    JOIN book.book_person bp
      ON bp.bookID = b.id 
    JOIN person p 
      ON p.id = bp.personID 
    WHERE lastname ILIKE '%something%' 
    ORDER BY b.title ASC, b.year DESC, b.volume ASC

给我错误:

ERROR:  42P01: missing FROM-clause entry for table "b"
LINE 12:         ORDER BY b.title ASC, b.year DESC, b.volume ASC
                          ^
LOCATION:  errorMissingRTE, parse_relation.c:3140

没有ORDER-clause 它工作正常。当我包含我想订购的 cols 时,它工作正常:

SELECT b.id, b.title, b.year, b.volume 
  FROM book.book b 
    WHERE title ILIKE '%something%' 
UNION
SELECT b.id, b.title, b.year, b.volume 
  FROM book.book b
    JOIN book.book_person bp
      ON bp.bookID = b.id 
    JOIN person p 
      ON p.id = bp.personID 
    WHERE lastname ILIKE '%something%' 
    ORDER BY "title" ASC, "year" DESC, "volume" ASC

有没有比包含更多列更好的方式来订购UNIONed queris?

标签: sqlpostgresqlunionpostgresql-9.5

解决方案


那是因为首先UNION创建结果,然后ORDER BY执行。titleetc 不再可作为UNION结果的引用。(基本上 UNION 比 ORDER BY 绑定得更紧密。)

因此,要绕过它,只需在第二个查询和 ORDER BY 语句周围加上括号,假设您只想订购该部分:

SELECT id
...
UNION
(SELECT id
...
ORDER BY title, etc)

如果您希望对完整查询进行排序,则您的 UNION 查询将必须返回所有排序列,然后您将对其进行选择:

SELECT id
FROM (
    SELECT id, title, etc
    ...
    UNION
    SELECT id, title, etc
) x
ORDER BY title, etc

推荐阅读