日期:2014-05-18  浏览次数:20694 次

这个sql语句怎么写?从章节1随机选取30道题,从章节2随机选取20道题目
这个sql语句怎么写?
我要从章节1随机选取30道题,从章节2随机选取20道题目
SQL code
select top 30 * from car where zhanjie=1 ORDER BY NEWID() union select top 20 * from car where zhanjie=2 ORDER BY NEWID() 这样写有错误


------解决方案--------------------
SQL code
SELECT * FROM (select top 30 * from car where zhanjie=1 ORDER BY NEWID()) A
UNION ALL
SELECT * FROM (select top 20 * from car where zhanjie=2 ORDER BY NEWID()) B

------解决方案--------------------
SQL code
SELECT * FROM (select top 30 * from car where zhanjie=1 ORDER BY NEWID()) A
UNION ALL
SELECT * FROM (select top 20 * from car where zhanjie=2 ORDER BY NEWID()) B

------解决方案--------------------
SQL code
select *
from
(
select top 30 * from car 
where zhanjie=1 
ORDER BY NEWID() 
) t
union 
select * 
from
(
select top 20 * 
from car 
where zhanjie=2 
ORDER BY NEWID() 
) r

------解决方案--------------------
SQL code
select * from (select top 30 * from car where zhanjie=1 ORDER BY NEWID()) t1
 union 
select * from ( select top 20 * from car where zhanjie=2 ORDER BY NEWID() )t2

------解决方案--------------------
用NEWID()效率太低,大数据量就死跷跷了
建议用TABLESTAMP
或者直接指定
SQL code
select 
*
from 
car
where id in (rand()*22,.....)

------解决方案--------------------
SQL code

SELECT * FROM 
(
select *,row_number() over(partition by zhangjie order by newid()) as rn
from car
) A
where (zhangjie=2 or zhangjie=1) and rn<31

------解决方案--------------------
SELECT top 30 timu
FROM car
WHERE zhangjie = 1
union
SELECT top 20 timu
FROME car
WHERE zhangjie = 2
不知可否。