SQL 联合问题
有人可以向我解释一下为什么 SQL 语句:
SELECT 'TEST1'
UNION SELECT 'TEST2'
UNION SELECT 'TEST3'
returns:
TEST2
TEST3
TEST1
我试图找出这方面 UNION
关键字背后的逻辑。 有没有办法让它返回:
TEST1
TEST2
TEST3
而不使用 ORDER BY
子句?换句话说,我可以控制UNION
语句的执行顺序吗?
如果重要的话,我使用 Postgre 9.0 和 PHP 作为我的语言
非常感谢, 布雷特
Can someone explain to me why the SQL statement:
SELECT 'TEST1'
UNION SELECT 'TEST2'
UNION SELECT 'TEST3'
returns:
TEST2
TEST3
TEST1
I am trying to figure out the logic behind the UNION
keyword in this aspect.
Is there a way I could get it to return:
TEST1
TEST2
TEST3
without using the ORDER BY
clause? In other words, can I control the execution order of the UNION
statements?
If it matters, I am using Postgre 9.0 and PHP as my language
Many thanks,
Brett
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
根据 UNION 的 PostgreSQL 文档:
According to the PostgreSQL docs for UNION:
UNION
语义是删除重复项。 PostgreSQL 使用哈希函数来删除重复项,结果按照键的哈希顺序输出。您可以使用
UNION ALL
,但除非您使用ORDER BY
子句,否则SQL 仍然不能保证顺序。产生:
而
产生:
UNION
semantics are that duplicates are removed. PostgreSQL is using a Hash function to remove the duplicates, and the results are comin out in the order of the key's hash.You can use
UNION ALL
, but SQL still doesn't guarantee an order unless you use theORDER BY
clause.Produces:
Whereas
Produces:
大多数数据库不保证没有
order by
语句的任何内容的顺序。在大多数情况下,union 可以允许数据库并行操作所有 3 个查询并尽快返回行。
Most databases do not guarantee the order of anything without an
order by
statement.union in most cases could allow the database to operate all 3 queries in parallel and return the rows as fast as possible.