Sql服务器联合但保持秩序

1zmg4dgp  于 2022-10-03  发布在  其他
关注(0)|答案(4)|浏览(135)

有没有一种方法可以联合两个表,但使第一个表中的行先出现在结果集中?

例如:

表1

name        surname
-------------------
John         Doe
Bob          Marley
Ras          Tafari

表2

name       surname
------------------
Lucky      Dube
Abby       Arnold

我希望结果集如下所示:

name        surname
-------------------
John        Doe
Bob         Marley 
Ras         Tafari
Lucky       Dube
Abby        Arnold

不幸的是,union不知何故对表进行了重新排序。有什么办法可以绕过这件事吗?

vwkv1x7d

vwkv1x7d1#

;WITH cte as (
    SELECT name, surname, 1 as n FROM table1
    UNION ALL
    SELECT name, surname, 2 as n FROM table2
    UNION ALL
    SELECT name, surname, 3 as n FROM table3
)
SELECT name, surname
FROM cte
ORDER BY n;
kokeuurv

kokeuurv2#

.像这样吗?

CREATE TABLE #Table1 (Names VARCHAR(50))
CREATE TABLE #Table2 (Names VARCHAR(50))

INSERT INTO #Table1
(
    Names
)
VALUES
    ('John Doe'), ('Bob Marley'), ('Ras Tafari') 

INSERT INTO #Table2
(
    Names
)
VALUES
    ('Lucky Dube'), ('Abby Arnold') 

SELECT ArbSeq   = 1, *
FROM #Table1
UNION ALL
SELECT ArbSeq   = 2, *
FROM #Table2
ORDER BY ArbSeq

应该注意的是,如果没有明确定义,则不能保证排序。如果该表具有聚集索引,则通常会按索引的顺序返回行--但这并不能保证。

r55awzrz

r55awzrz3#

试试这个:-

Select * 
from
( 
Select name,surname, 1 as filter
from  Table1
Union all
Select name,surname , 2 as filter
from Table2
)
order by filter
js5cn81o

js5cn81o4#

保证输出顺序的唯一方法是使用ORDER BY

SELECT name,surname,1 as rs
FROM table1
UNION ALL
SELECT name,surname,2
FROM table2
ORDER BY rs

如果不希望rs出现在最终结果集中,请将UNION作为子查询:

SELECT name,surname
FROM (
  SELECT name,surname,1 as rs
  FROM table1
  UNION ALL
  SELECT name,surname,2
  FROM table2
) t
ORDER BY rs

相关问题