我有两个表 - table1和table2。两者都包含两列 - rollnum,name。现在我想从table1中选择所有行,并从table2中随机选择5行。我写得像这样
select rollnum,name from table1 union (select top 5 rollnum,name from table2 order by NEWID())
但是显示错误ORDER BY items must appear in the select list if the statement contains a UNION, INTERSECT or EXCEPT operator.
请帮忙。我认为错误在于NEWID()。这里rollnum是主键
答案 0 :(得分:1)
问题在于括号。试试这个
select rollnum,name from table1
union
select * from (select top 5 rollnum,name from table2 order by NEWID()) t
如果您有重复的参赛作品,可能需要考虑使用union all
代替union
答案 1 :(得分:-1)
试试这个..
SELECT rollnum AS 'NewID' ,
name
FROM table1
UNION
SELECT TOP 5
rollnum ,
name
FROM table2
ORDER BY NewID
NEWID()是一个为声明为uniqueidentifier数据类型的变量赋值的函数