使用 2 个以上表的联合覆盖按字母顺序排列的默

Override alphabetical default ORDER BY with a UNION of 2+ tables?(使用 2 个以上表的联合覆盖按字母顺序排列的默认 ORDER BY?)
本文介绍了使用 2 个以上表的联合覆盖按字母顺序排列的默认 ORDER BY?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

非常简单的问题...我有 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Execute complex raw SQL query in EF6(在EF6中执行复杂的原始SQL查询)
Hibernate reactive No Vert.x context active in aws rds(AWS RDS中的休眠反应性非Vert.x上下文处于活动状态)
Bulk insert with mysql2 and NodeJs throws 500(使用mysql2和NodeJS的大容量插入抛出500)
Flask + PyMySQL giving error no attribute #39;settimeout#39;(FlASK+PyMySQL给出错误,没有属性#39;setTimeout#39;)
auto_increment column for a group of rows?(一组行的AUTO_INCREMENT列?)
Sort by ID DESC(按ID代码排序)