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

浏览:24日期:2023-07-21

--合并重复行select * from Aunion select * from B

--不合并重复行select * from Aunion allselect * from B

按某个字段排序--合并重复行select *from (select * from Aunion select * from B) AS Torder by 字段名

--不合并重复行select *from (select * from Aunion allselect * from B) AS Torder by 字段名

//sql server版Select * From (select top 2 id,adddate,title,url from bArticle where ClassId='1' order by adddate desc) AUnion AllSelect * From (select top 2 id,adddate,title,url from bArticle where ClassId='2' order by adddate desc) BUnion AllSelect * From (select top 2 id,adddate,title,url from bArticle where ClassId='3' order by adddate desc) CUnion AllSelect * 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) AUnion AllSelect * From (select id,adddate,title,url from bArticle where ClassId='2' order by adddate desc limit 0,2) BUnion AllSelect * From (select id,adddate,title,url from bArticle where ClassId='3' order by adddate desc limit 0,2) CUnion AllSelect * From (select id,adddate,title,url from bArticle where ClassId='4' order by adddate desc limit 0,2) D

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

相关文章: