每个取top 5,既然是随机的取,那么就order by newid()就是了三,然后把所有数据union起来就得了。所以我⽴即给出了答案:
select top 5 * from xxx where type=1 order by newid() union
select top 5 * from xxx where type=0 order by newid()
但是那个兄弟说不对,语法有错,我乍⼀看,好像没有问题把,于是让他把表定义发给我,我在本机试⼀下,表定义是: CREATE TABLE [dbo].[Question]( [id] [int] IDENTITY(1,1) NOT NULL, [question] [varchar](50) NOT NULL, [answer] [varchar](50) NOT NULL, [type] [bit] NOT NULL,
CONSTRAINT [PK_Question] PRIMARY KEY CLUSTERED (
[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF,ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY]
将语句输进SSMS,结果系统还真是报错了:Incorrect syntax near the keyword 'ORDER'. 怎么回事啊?于是单独执⾏
select top 5 * from dbo.Question where [type]=1
ORDER BY newid()
下⾯的半句也是⼀样的语法结构,也没有错误。但是把这两个查询union起来就错了。奇怪啊。既然提⽰是order附近有错,那么我将order给去掉:
(select top 5 * from dbo.Question where [type]=1 )
UNION
(select top 5 * from dbo.Question where [type]=0 )
也没有错啊。也就是说在union⼦句中的查询不能⽤order by。但是这⼉我必须要⽤order by啊,要不然我怎么取出随机的5条记录?不⽤union可以不?可以啊,创建⼀个临时表,将查询出来的5条数据插进去,另外5条也是。然后再查询临时表,但是能不使⽤临时表就尽量不要使⽤临时表,何必弄的那么复杂。
⼜要⽤order by ⼜要⽤union,怎么办?order by不能直接出现在union的⼦句中,但是可以出现在⼦句的⼦句中啊!于是查询最终改写成了: SELECT * FROM
(select (5) * from dbo.Question where [type]=1 ORDER BY newid() ) t1 UNION
SELECT * FROM
(select (5) * from dbo.Question where [type]=0 ORDER BY newid()) t2
因篇幅问题不能全部显示,请点此查看更多更全内容