SQL A Union B的结果与A + B不同?

时间:2018-03-13 20:28:50

标签: sql union

我使用Union来合并两个SQL查询,但结果不同于两个不同查询的组合。 下面是我的SQL代码:

(SELECT CONCAT(Name, '(', LEFT(Occupation, 1), ')')
FROM OCCUPATIONS
ORDER BY Name ASC)
UNION
(SELECT CONCAT('There are a total of ', COUNT(Occupation), ' ', 
LOWER(Occupation), 's.')
FROM OCCUPATIONS
GROUP BY Occupation
ORDER BY Occupation ASC)

如果我只运行查询的前半部分,我会得到以下结果:

Aamina(D) 
Ashley(P) 
Belvet(P) 
Britney(P) 
Christeen(S) 
Eve(A) 
Jane(S) 
Jennifer(A) 
Jenny(S) 
Julia(D) 
Ketty(A)  
Kristeen(S) 
Maria(P) 
Meera(P) 
Naomi(P) 
Priya(D) 
Priyanka(P) 
Samantha(A) 

如果我只运行查询的后半部分,我会得到以下结果:

There are a total of 4 actors. 
There are a total of 3 doctors. 
There are a total of 7 professors. 
There are a total of 4 singers. 

以上两个结果均按预期顺序排列。但是,如果我运行所有查询,我会得到以下结果:

Ashley(P) 
Samantha(A) 
Julia(D) 
Britney(P) 
Maria(P) 
Meera(P) 
Priya(D) 
Priyanka(P) 
Jennifer(A) 
Ketty(A) 
Belvet(P) 
Naomi(P) 
Jane(S) 
Jenny(S) 
Kristeen(S) 
Christeen(S) 
Eve(A) 
Aamina(D) 
There are a total of 4 actors. 
There are a total of 3 doctors. 
There are a total of 7 professors. 
There are a total of 4 singers. 

正如您可能注意到的那样,上半部的顺序被搞砸了。有谁知道为什么? Union如何与写两个单独的SQL查询不同?谢谢!

1 个答案:

答案 0 :(得分:2)

订单没有“搞砸”。整个查询没有order by,仅适用于子查询。订单不会保留。您正在使用UNION,这会删除重复项。

执行此查询的安全方法是:

select str
from ((select concat(Name, '(', LEFT(Occupation, 1), ')') as str, 1 as which
       from OCCUPATIONS
      ) union all
      (select concat('There are a total of ', COUNT(Occupation), ' ', 
lower(Occupation), 's.') as str, 2 as which
       from OCCUPATIONS
       group by occupation
      )
     ) o
order by which, str