UNION奇怪的行为 - MSSQL

时间:2016-04-28 09:26:42

标签: sql-server

我们有两个简单的查询

1

SELECT TOP 1 bankID
FROM [bank] WHERE [bankID] = 91
UNION 
SELECT TOP 1 bankID
FROM [bank] WHERE [bankID] = (SELECT [bankID] FROM [bank] WHERE bankID = 83)

按预期返回:

bankID
1    91
2    83

2

SELECT TOP 1 bankID 
FROM [bank] WHERE [bankID] = 91
UNION 
SELECT TOP 1 bankID
FROM [bank] WHERE [bankID] = (SELECT [bankID] FROM [bank] WHERE bankID > 82 AND bankID < 84)

返回:

bankID
1    83
2    91

订单相反。为什么呢?

当我们在第一个联合查询中更改条件时,结果符合预期。

SELECT TOP 1 bankID
FROM [bank] WHERE [bankID] = 42
UNION 
SELECT TOP 1 bankID
FROM [bank] WHERE [bankID] = (SELECT [bankID] FROM [bank] WHERE bankID = 83)
SELECT TOP 1 bankID
FROM [bank] WHERE [bankID] = 42
UNION 
SELECT TOP 1 bankID
FROM [bank] WHERE [bankID] = (SELECT [bankID] FROM [bank] WHERE bankID > 82 AND bankID < 84)

两者的结果是:

       bankID
    1    42
    2    83

再次,为什么?

SQLServer 2012

1 个答案:

答案 0 :(得分:1)

订单无法保证,直到您指定订单。如果您想保留订单,请执行以下操作

select * from  A
union all
select * from b order by id --now you will get output order based on id

<强>更新 所有RDBMS都基于Settheory.So集合中的元素没有任何order.TSQL也基于集合论在很多方面。表应该被视为一个集合,表中的行不以任何顺序存储.SQL是可以根据索引,冷缓存,计划等许多标准,以任意顺序自由检索行...

所以来你的示例联合所有两个集合再次是一个集合,并且不保证每次都获得相同的订单

select 1 as t
union all
select 2
union all
select 0

<强>输出:

t
--
1
2
0

在您订购之前,您不会保证每次都能获得相同的订单。

select 1 as t
union all
select 2
union all
select 0 order by t

同样适用于CTE&#39; s衍生表

中的订单
 with cte
as
(
   select top 100% from table order by somecolumn
)
select * from cte

即使您在cte中订购,也不会每次都获得默认订单,直到您在外部条款中订购

with cte
as
(
   select top 100% from table order by somecolumn
)
select * from cte order by somecolumn