sql的union使用问题
麻烦大虾看一下代码,,运行union 报错是怎么回事啊
insert into caogen(id,no,tittle,author,contents)
select top 158 * from _TangSi
where Author not in( select Author from huangjia)and Author<>'无名氏' order by NEWID()
union
select * from _TangSi where Author='无名氏'
[解决办法]
分成两句... 要不你说说报错是啥吧。
[解决办法]
order by NEWID() 不能加order by 改下就可以了
insert into caogen(id,no,tittle,author,contents)
select * from (select top 158 * from _TangSi
where Author not in( select Author from huangjia)and Author<>'无名氏' order by NEWID() ) a
union
select * from _TangSi where Author='无名氏'
[解决办法]
应该是楼上说的那样,使用union时,不能带有order by
insert into caogen(id,no,tittle,author,contents)
select top 158 * from _TangSi
where Author not in( select Author from huangjia)and Author<>'无名氏'
union
select * from _TangSi where Author='无名氏'
[解决办法]
insert into caogen(id,no,tittle,author,contents)
select * from (select top 158 * from _TangSi
where Author not in( select Author from huangjia)and Author<>'无名氏' union
select * from _TangSi where Author='无名氏')as t order by NEWID()
[解决办法]
with cte
as
(
select top 158 * from _TangSi
where Author not in( select Author from huangjia)and Author<>'无名氏' order by NEWID()
)
insert into caogen(id,no,tittle,author,contents)
select * from cte
union
select * from _TangSi where Author='无名氏'
union 连接查询中不能使用order by 语句,必须是类似上楼的
select * from (select top 158 * from _TangSi
where Author not in( select Author from huangjia)and Author<>'无名氏' union
select * from _TangSi where Author='无名氏')as t order by NEWID()
最后使用order by。
或者使用cte 语句定义也可以,参考我的sql语句
[解决办法]
在使用 UNION、EXCEPT 或 INTERSECT 运算符的查询中,只允许在语句末尾使用 ORDER BY。 只有在顶级查询而不是子查询中指定了 UNION、EXCEPT 和 INTERSECT 时,此限制才适用。