注册 登录
编程论坛 SQL Server论坛

sql随机问题

shangxisen 发布于 2010-07-22 17:49, 1151 次点击
我现在遇到的问题是,我要从两个不同的表中同时随机取出几条记录,然后把这些记录在放在一张表里显示,如
select top 5 * from stu1 order by newdid()     select top 5 * from stu2 order by newdid()这样写的话会出现两张表,我试过用select top 5 * from stu1 order by newid() uoion select top 5 * from stu2 order by newid()
但是提示错误,那位高手能告诉我一下,应该怎么把这两个连在一起?
12 回复
#2
cnfarer2010-07-22 20:58
select top 5 * into #xx from stu1 order by newid()
select top 5 * into #yy from stu2 order by newid()
select * from #xx union all select * from #yy
drop table #xx,#yy
#3
dearwolf41282010-07-23 09:08
利用union联合的表需要列的类型一致,你联合不上,估计你两个表的某个列的类型不一致,你需要使他们类型一致;另外给他们排序只能在最后一个查询表中使用,你两个都用了,也是不对的;建议你多看看书或技术手册
#4
aei1352010-07-23 09:31
要取随机数可以先将两表连接起来再取的,当然由于排序的列不在选择列表中,所以不能直接加在第二个表的后面
select * from
(select top 5 * from stu1
union
select top 5 * from stu2) x order by newid()
#5
cnfarer2010-07-23 16:33
回复 4楼 aei135
这个不随机
#6
cnfarer2010-07-23 16:33
回复 3楼 dearwolf4128
union是不能和order by一起用的啊!
#7
dearwolf41282010-07-23 18:03
union是可以和order by一起使用的,只不过要放在最后一个表上,不能放在前面的表上,是给前面的表用了也不起作用!
#8
huxiangwenhu2010-07-23 22:10
我试过了一下上面两位楼主的方法,都出现了以下错误:
服务器: 消息 205,级别 16,状态 1,行 3
包含 UNION 运算符的 SQL 语句中的所有查询都必须在目标列表中具有相同数目的表达式。
  不知道是我的表出现了问题还是怎么的。两个表为:


只有本站会员才能查看附件,请 登录

只有本站会员才能查看附件,请 登录

查询语句为:
select * from
(select top 3 * from course
union
select top 3 * from score) x order by cno

select top 3 * into #xx from score order by cno
select top 3 * into #yy from course order by cno
select * from #xx union all select * from #yy
#9
cnfarer2010-07-24 17:21
回复 8楼 huxiangwenhu
你的这两表字段明显是不同的,当然不能UNION了!
#10
cnfarer2010-07-24 17:23
回复 7楼 dearwolf4128
不起作用还叫可用?
#11
shangxisen2010-07-27 13:21
感谢各位,问题应经解决,order by 和union可以在一起用
select * from(select top 5 * from table1 order by newid())A union
select * from (select top 5 * from table1 order by newid())B就可以了
#12
shangxisen2010-07-27 13:21
回复 10楼 cnfarer
感谢各位,问题应经解决,order by 和union可以在一起用
select * from(select top 5 * from table1 order by newid())A union
select * from (select top 5 * from table1 order by newid())B就可以了
#13
shangxisen2010-07-27 13:22
回复 8楼 huxiangwenhu
感谢各位,问题应经解决,order by 和union可以在一起用
select * from(select top 5 * from table1 order by newid())A union
select * from (select top 5 * from table1 order by newid())B就可以了
1