当前位置:K88软件开发文章中心编程语言SQLSQL01 → 文章内容

一条sql语句实现合并两个查询结果

减小字体 增大字体 作者:wangsdong     来源:asp编程网  发布时间:2018-12-30 9:13:42

'功能:一条sql语句实现合并两个查询结果
'作者:wangsdong
'来源:www.aspprogram.cn
'。

表名:table
字段:ID 
username ytime
需要实现的结果是:
查询1:
 
 
select top 5 
* from table where Id>
20 order by id asc
查询2:
 
 
select top 5 
* from table where id<
20 order by id desc
并且再将查询1和查询2之和,再按照ID的倒序。原以为:查询2好办,本来就倒序了,并且都小于20,所以这个不需要改动的。现在需要再将查询1进行一次排序就行了。
于是写了一个sql语句:
select * from (select top 5 
* from table where Id>
20 order by id asc) order by id desc
union all
select top 5 
* from table where Id>
20 order by id asc
运行的结果居然是:id>
20的那5条记录没有倒序。

必须换种写法了:
select * from (select top 5 
* from table where Id>
20 order by id asc
union all
select top 5 
* from table where Id>
20 order by id asc) order by id desc
思路是:先将两个查询合并到一起,然后再进行倒序。终于搞定了。



一条sql语句实现合并两个查询结果