問題描述
非常簡單的問題...我有 4 個表,它們是 UNION
結合在一起的,如下所示:
Really quick question... I have 4 tables that are UNION
-ed together like so:
SELECT * FROM table1
UNION
SELECT * FROM table2
UNION
SELECT * FROM table3
UNION
SELECT * FROM table4
不指定 ORDER BY
,查詢按字母升序排列第一列(在我的例子中恰好是 varchar
類型).我也不想要 ORDER BY [Column1] DESC
.
Without specifying an ORDER BY
, the query orders by the first column in ascending alphabetical order (which in my case happens to be a varchar
type). I don't want ORDER BY [Column1] DESC
either.
我只是想按照與表本身UNION
-ed 相同的順序對結果進行排序.1、2、3、4.
I simply want to order the results in the same order as the tables themselves are UNION
-ed. 1, 2, 3, 4.
有沒有簡單的方法可以做到這一點?
Is there a simply way to do this?
謝謝!!
推薦答案
一種方式
SELECT *,1 as SortOrder FROM table1
UNION
SELECT *,2 FROM table2
UNION
SELECT *,3 FROM table3
UNION
SELECT *,4 FROM table4
order by SortOrder
發生的事情是你使用了 UNION,然后 sql server 使結果集不同,為了做到這一點,它需要對表進行排序
what happens is that you are using UNION, sql server then makes the result set distinct, in order to do that it needs to sort the tables
UNION ALL
有什么不同嗎?
這篇關于使用 2 個以上表的聯合覆蓋按字母順序排列的默認 ORDER BY?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!