最近我一直在用sql语句中的UNION函数进行试验,但是我已经到了一个我无法得到我想要的东西的地步。
所以我试图连接两个查询,一个给我输出
ID | DATE | X
29 | 2016-07-31 20:00:00 | 0
27 | 2016-07-31 23:00:00 | 0
26 | 2016-07-31 23:22:00 | 0
使用此查询:
SELECT * FROM table_entries WHERE closed='0' ORDER BY start_date ASC
另一个给我这个输出
ID | DATE | X
28 | 2016-07-31 15:00:00 | 1
25 | 2016-07-31 01:00:00 | 1
24 | 2016-07-31 00:19:00 | 1
使用此查询:
SELECT * FROM table_entries WHERE closed='1' ORDER BY start_date DESC
所以我尝试用这种方式组合它们:
(SELECT * FROM table_entries WHERE closed='0' ORDER BY start_date ASC) UNION (SELECT * FROM table_entries WHERE closed='1' ORDER BY start_date DESC)
但不是预期的
陈述ID | DATE | X
29 | 2016-07-31 20:00:00 | 0
27 | 2016-07-31 23:00:00 | 0
26 | 2016-07-31 23:22:00 | 0
28 | 2016-07-31 15:00:00 | 1
25 | 2016-07-31 01:00:00 | 1
24 | 2016-07-31 00:19:00 | 1
它给了我这个回报
ID | DATE | X
26 | 2016-07-31 23:22:00 | 0
27 | 2016-07-31 23:00:00 | 0
29 | 2016-07-31 20:00:00 | 0
24 | 2016-07-31 00:19:00 | 1
25 | 2016-07-31 01:00:00 | 1
28 | 2016-07-31 15:00:00 | 1
我应该改变什么才能在开始时完成我想要的东西,或者将这些陈述“绑定”在一起,以便它们相互叠加。
亲切的问候
答案 0 :(得分:0)
假设我理解正确,您可以在conditional ordering
中使用case
与order by
:
SELECT * FROM matches WHERE closed='0'
UNION
SELECT * FROM matches WHERE closed='1'
ORDER BY closed,
CASE WHEN closed = 0 THEN start_date ELSE '9999-12-31' END,
CASE WHEN closed = 1 THEN start_date ELSE '1000-01-01' END DESC
答案 1 :(得分:0)
您编写的查询在末尾指定DESC而不是ASC。它应该是这样的:
(SELECT * FROM matches WHERE closed='0' ORDER BY start_date ASC)
UNION
(SELECT * FROM matches WHERE closed='1' ORDER BY start_date ASC)
答案 2 :(得分:0)
根本不需要UNION
此查询:
SELECT *
FROM table_entries
WHERE closed IN ('0', '1')
ORDER BY closed,
(CASE WHEN closed = '0' THEN start_date END) ASC,
(CASE WHEN closed = '1' THEN start_date END) DESC;
理解SQL结果集没有固有的排序(除少数特殊情况外)非常非常重要,除非查询具有ORDER BY
子句。这是因为SQL基于无序集的概念。
UNION
需要删除重复项,这是额外的处理。但是,除非最外层ORDER BY
有SELECT
,否则不应该假定查询的顺序。