sql - PostgreSQL:如何对未包含列的联合查询进行排序?
问题描述
我尝试ORDER
2 UNION
ed 查询。运行这个:
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
有没有比包含更多列更好的方式来订购UNION
ed queris?
解决方案
那是因为首先UNION
创建结果,然后ORDER BY
执行。title
etc 不再可作为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
推荐阅读
- react-native - TypeError:reactDevTools.connectToDevTools 不是函数
- sql - 根据另一个表中多列之间的范围在表中插入多行
- javascript - 如何根据用户输入在数组中进行隔离?
- angular - Angular2将值绑定到结构指令
- azure-automation - 克隆计算机的 Log Analytics 中的相同 SourceComputerId
- list - 颤振:从列表中删除卡不起作用
- javascript - Vue.js 如何在 v-for 循环中切换单个 v-if div?
- c# - 从 MainViewModel (WPF, C#) 访问属性
- sql-server - 以另一种形式保存数据时,Vb.Net在主形式中更新Datagridview
- javascript - 获取序列中的下一个值,而不使用生成器函数单击带有 javascript 的按钮