当前位置: 代码迷 >> SQL >> sql话语查询结果合并union 和union all用法
  详细解决方案

sql话语查询结果合并union 和union all用法

热度:36   发布时间:2016-05-05 14:27:34.0
sql语句查询结果合并union 和union all用法

?

sql语句查询结果合并union 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 byadddate desc) A
Union All
Select * From (
select top 2 id,adddate,title,url from bArticle where ClassId='2' order byadddate desc) B
Union All
Select * From (
select top 2 id,adddate,title,url from bArticle where ClassId='3' order byadddate desc) C
Union All
Select * From (
select top 2 id,adddate,title,url from bArticle where ClassId='4' order byadddate desc) D


//mysql

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

DB2里使用union时一定要注意相对应的字段一定是数据类型一样,输出时可以任意显示的列,但不能输出不同类型或不同表结构。因为这样会出错。

?

?