您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息
免费发信息
三六零分类信息网 > 十堰分类信息网,免费分类信息发布

union与order by合并使用_MySQL

2024/5/6 2:13:56发布57次查看
bitscn.com
union与order by合并使用
在sql语句中,union关键字多用来将并列的多组查询结果(表)合并成一个结果(表),简单实例如下:
select [id],[name],[comment] from [product1]unionselect [id],[name],[comment] from [product2]
上面的代码可以实现将从product1和product2两张表合并成一个表,如果您只是希望合并两张表中符合特定条件的记录抑或是合并两张表各自的前n条记录,那么您的代码可能会像下面这样写:
select [id],[name],[comment] from [product1] wherelen([name]) > 5unionselect [id],[name],[comment] from [product2] where [id] in (11,20) and [comment] is not nullselect top n [id],[name],[comment] from [product1]unionselect top n [id],[name],[comment] from [product2]
this is so easy!但是假如您希望从包含type字段的某表中根据type分别随机筛选n条记录并将结果合并成一张表,您可能会像下面这样写:
select top n [id],[name],[comment] from [product] where [type]='type1' order by newid()unionselect top n [id],[name],[comment] from [product] where [type]='type2' order by newid()unionselect top n [id],[name],[comment] from [product] where [type]='type3' order by newid()unionselect top n [id],[name],[comment] from [product] where [type]='type4' order by newid()unionselect top n [id],[name],[comment] from [product] where [type]='type5' order by newid()unionselect top n [id],[name],[comment] from [product] where [type]='type6' order by newid()unionselect top n [id],[name],[comment] from [product] where [type]='type7' order by newid()
在查询分析器中执行如上语句会报错,这个问题起初会令您觉得union在这方面似乎有点软弱,难道union和order by就不能共存吗?当然可以,下面的代码或许能实现与上面代码希望实现的相同功能:
select * from (select top n [id],[name],[comment] from [product] where [type]='type1' order by newid()) as [product1] union select * from (select top n [id],[name],[comment] from [product] where [type]='type2' order by newid()) as [product2] union select * from (select top n [id],[name],[comment] from [product] where [type]='type3' order by newid()) as [product3] union select * from (select top n [id],[name],[comment] from [product] where [type]='type4' order by newid()) as [product4] union select * from (select top n [id],[name],[comment] from [product] where [type]='type5' order by newid()) as [product5] union select * from (select top n [id],[name],[comment] from [product] where [type]='type6' order by newid()) as [product6] union select * from (select top n [id],[name],[comment] from [product] where [type]='type7' order by newid()) as [product7]
bitscn.com
十堰分类信息网,免费分类信息发布

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录