我正在使用UNION
从3个不同的表中进行选择:
SELECT DISTINCT car AS searchword, 0 AS priority FROM Cars
UNION
SELECT DISTINCT animal AS searchword, 1 AS priority FROM Animals WHERE animal <> 'dog'
UNION
SELECT color AS searchword, 2 AS priority FROM (SELECT TOP 100 PERCENT color FROM Colors ORDER BY [count] DESC) as a
ORDER BY priority ASC
但是,当我运行此命令时,以下SELECT
不会保留其顺序:
SELECT color AS searchword, 2 AS priority FROM (SELECT TOP 100 PERCENT color FROM Colors ORDER BY [count] DESC) as a
如何解决?我需要这样的结果集:Cars
,Animals
,Colors
,我无法混合使用SELECTS。并且Colors
需要通过count
列进行排序。
答案 0 :(得分:2)
在第二个代码块中,您的ORDER BY子句位于子查询内部。离开子查询并移至外部查询后,将没有ORDER BY子句。因此,不能保证订购。
在您的第一个代码块中,实际上有一个ORDER BY子句,因此在这种情况下可以保证您的订单,但是它位于“优先级”上。
如果要按“优先级”排序,然后按子查询中的“计数”排序,则必须找到一种方法来获取“计数”作为外部查询的一部分:
select searchword = car,
priority = 0,
[count] = null
from Cars
union
select animal, 1, null
from Animals
where animal <> 'dog'
union
select color, 2, [count]
from colors
order by priority ASC, count desc
在这种情况下,重构完全消除了对子查询的需求。
顺便说一句,我摆脱了一些不必要的区别(工会已经做到了区别)。