我有两个与Union“合并”的查询:
A
union
B
我希望结果按特定列排序。
例如:
A
id sum dateissue
5 30 1.1.15
8 14 2.4.15
乙
id sum dateissue
13 30 1.4.12
8 14 4.4.15
联盟之后的期望结果 dateissue列
id sum dateissue
13 30 1.4.12 : from B
5 30 1.1.15 : from A
8 14 2.4.15 : from A
8 14 4.4.15 : from B
我试着做
(A)
Union
(B)
order by dateissue
但它给出了错误:
错误:列“dateissue”不存在
如何对联合的结果进行排序?
答案 0 :(得分:2)
您只需要确保第一个选择实际上提取'dateissue',即
select id, sum, dateissue
from a
where...
union
select id, sum, dateissue
from a
where...
order by dateissue;
为了澄清,'order by'应用于完整的结果集(在联合之后)。
答案 1 :(得分:1)
SELECT *
FROM
(
SELECT id, sum, dateissue FROM A
UNION ALL
SELECT id, sum, dateissue FROM B
) dum
ORDER BY dateissue
订单在SELECT *
中有影响SELECT * FROM (
SELECT id, sum, dateissue FROM A
UNION ALL
SELECT id, sum, dateissue FROM B
) dum ->
id sum dateissue
5 30 1.1.15
8 14 2.4.15
13 30 1.4.12
8 14 4.4.15
ORDER BY dateissue ->
id sum dateissue
13 30 1.4.12
5 30 1.1.15
8 14 2.4.15
8 14 4.4.15
你可以使用UNION ALL:What is the difference between UNION and UNION ALL?以防同一行
答案 2 :(得分:0)
试试这个:
SELECT * FROM A
UNION
SELECT * FROM B
ORDER BY dateissue;