asdfasfasdf

如何联合使用Union和Order by

如果使用类似下面的SQL语句:

select columnA, columnB from tableA where columnA = 'Condition 1'
union
select columnC, columnD from tableB where columnC = 'Condition 1'
order by columnA asc

 系统会报错:
消息 207,级别 16,状态 1,第 4 行
列名 'columnA' 无效。
消息 104,级别 16,状态 1,第 4 行
如果该语句包含 UNION、INTERSECT 或 EXCEPT 运算符,则 ORDER BY 项必须出现在选择列表中。

问题原因:
既然把多行给union了,把每列叫成什么名字都是不妥当的。。。只要采用列的序号即可。

select columnA, columnB from tableA where columnA = 'Condition 1'
union
select columnC, columnD from tableB where columnC = 'Condition 1'
order by 2 asc

这里需要注意的是,序号从1开始,如果指定的序号不在允许的范围内,系统会报出一个异常:

select columnA, columnB from tableA where columnA = 'Condition 1'
union
select columnC, columnD from tableB where columnC = 'Condition 1'
order by 4 asc

会报错:
消息 108,级别 16,状态 1,第 1 行
ORDER BY 位置号 4 超出了选择列表中项数的范围。
消息 104,级别 16,状态 1,第 1 行
如果该语句包含 UNION、INTERSECT 或 EXCEPT 运算符,则 ORDER BY 项必须出现在选择列表中。

以上所有的提示都是在SQL Server 2005 SSMS中调试得出的。

关于ORDER BY的详细信息,可以参考以下文章:
http://msdn2.microsoft.com/zh-cn/library/ms188385.aspx

关于UNION的详细信息,可以参考以下文章:
http://msdn2.microsoft.com/zh-cn/library/ms180026.aspx

posted on 2007-04-10 15:42  明达  阅读(3791)  评论(0编辑  收藏  举报

导航