服务器之家:专注于服务器技术及软件下载分享
分类导航

Mysql|Sql Server|Oracle|Redis|MongoDB|PostgreSQL|Sqlite|DB2|mariadb|Access|数据库技术|

服务器之家 - 数据库 - Sql Server - sql 查询结果合并union all用法_数据库技巧

sql 查询结果合并union all用法_数据库技巧

2019-11-18 15:00mssql教程网 Sql Server

sql语句查询结果合并union all用法_数据库技巧,需要的朋友可以参考下。

代码如下:


--合并重复行 
select * from A 
union 
select * from B 


--不合并重复行 
select * from A 
union all 
select * from B 


按某个字段排序 
--合并重复行 
select * 
from ( 
select * from A 
union 
select * from B) AS T 
order by 字段名 

--不合并重复行 
select * 
from ( 
select * from A 
union all 
select * from B) AS T 
order by 字段名 

//sql server版 
Select * From ( 
select top 2 id,adddate,title,url from bArticle where ClassId=1 order by adddate desc) A 
Union All 
Select * From ( 
select top 2 id,adddate,title,url from bArticle where ClassId=2 order by adddate desc) B 
Union All 
Select * From ( 
select top 2 id,adddate,title,url from bArticle where ClassId=3 order by adddate desc) C 
Union All 
Select * From ( 
select top 2 id,adddate,title,url from bArticle where ClassId=4 order by adddate desc) D 


//mysql版 
Select * From ( 
select id,adddate,title,url from bArticle where ClassId=1 order by adddate desc limit 0,2) A 
Union All 
Select * From ( 
select id,adddate,title,url from bArticle where ClassId=2 order by adddate desc limit 0,2) B 
Union All 
Select * From ( 
select id,adddate,title,url from bArticle where ClassId=3 order by adddate desc limit 0,2) C 
Union All 
Select * From ( 
select id,adddate,title,url from bArticle where ClassId=4 order by adddate desc limit 0,2) D

延伸 · 阅读

精彩推荐