1

我真的陷入了 UNION ALL 加入,下面是 senario

如果我单独运行此查询,我会得到以下结果

1) Select salary as result from employee 
   where empno = '111628548' and seqno = 4   
   order by seqno Desc

result
------ 
$7000
$3000

2) Select descofemp as result from empdetail
   where empno = '111628548' and seqno = 4 
   order by seqno Desc

result
------
very good employee
good employee

以上都导致字符串,所以列是相同的类型。但是当我用联合加入上述两个查询时,我得到了类似的东西

With s1 as (Select salary from employee 
   where empno = '111628548' and seqno = 4   
   order by seqno Desc),

s2 as (Select descofemp from empdetail
   where empno = '111628548' and seqno = 4 
   order by seqno Desc
)
select * from s1                                                    
Union ALL                                                           
select * from s2  

Result
------
$3000
$7000
very good employee
good employee

你可以在这里看到薪水的顺序已经改变,我尝试了很多事情,但我无法理解为什么 UNION ALL 中的顺序会改变,如果是的话,有人知道或面临这个问题吗?请分享一些关于如何解决它。

先感谢您。

问候莫娜

4

1 回答 1

3

Union 不保证结果的顺序。但是,您可以添加订购信息并使用它:

With s1 as (Select salary as col, row_number() over (order by seqno desc) as seqnum
   from employee 
   where empno = '111628548' and seqno = 4   
  ),  
s2 as (Select descofemp as col , row_number() over (order by seqno desc) as seqnum
   from empdetail
   where empno = '111628548' and seqno = 4 
)
select col
from (select * from s1                                                    
      Union ALL                                                           
      select * from s2
     ) t
order by seqnum
于 2013-06-20T01:05:08.303 回答