让UNION与ORDER BY并存于SQL语句当中

在SQL语句中,UNION关键字多用来将并列的多组查询结果(表)合并成一个结果(表),简单实例如下:

SELECT [Id],[Name],[Comment] FROM [Product1] UNION SELECT [Id],[Name],[Comment] FROM [Product2]

上面的代码可以实现将从Product1和Product2两张表合并成一个表,如果您只是希望合并两张表中符合特定条件的记录抑或是合并两张表各自的前N条记录,那么您的代码可能会像下面这样写:

SELECT [Id],[Name],[Comment] FROM [Product1] WHERE LEN([Name]) > 5 UNION SELECT [Id],[Name],[Comment] FROM [Product2] WHERE [Id] IN (11,20) AND [Comment] IS NOT NULL
SELECT TOP N [Id],[Name],[Comment] FROM [Product1] UNION

SELECT 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() UNION SELECT TOP N [Id],[Name],[Comment] FROM [Product] WHERE [Type]='TYPE2' ORDER BY NEWID() UNION SELECT TOP N [Id],[Name],[Comment] FROM [Product] WHERE [Type]='TYPE3' ORDER BY NEWID() UNION SELECT TOP N [Id],[Name],[Comment] FROM [Product] WHERE [Type]='TYPE4' ORDER BY NEWID() UNION SELECT TOP N [Id],[Name],[Comment] FROM [Product] WHERE [Type]='TYPE5' ORDER BY NEWID() UNION SELECT TOP N [Id],[Name],[Comment] FROM [Product] WHERE [Type]='TYPE6' ORDER BY NEWID() UNION SELECT TOP N [Id]

转载于:https://www.cnblogs.com/qfb620/p/4181836.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值