今天在开发一个存储过程的是遇到一个问题,Oracle数据库多超过2个表使用union all 查询结果进行排序时报排序字段无效。经一番周折终于解决了问题,在此分享一下解决方法。
3张数据库表:t1,t2,t3
t1表字段id,name,sex
t2表字段no,name,sex
t3表字段sno,name,grad
2表查询语句:select id,name,sex from (select tb.* from (
select id,name,sex from t1
union all
select no, name,sex from t2
order by id desc) tb)
2表这样查询是没有问题
但是3表查询就会报异常。
3表原来的查询语句
select id,name,sex from (select tb.* from (
select id,name,sex from t1
union all
select no, name,sex from t2
union all
select sno,name,grad from t3
order by id desc) tb)
这样查询会报id字段无效,
解决办法是在第二个表为排序字段加一个别名
如下:
select id,name,sex from (select tb.* from (
select id,name,sex from t1
union all
select no id, name,sex from t2
union all
select sno,name,grad from t3
order by id desc) tb)