0
点赞
收藏
分享

微信扫一扫

union all 和 order by 连用的问题


在mybatis中,如果union 或者union all 和 order by连用,会发现运行会报错:

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'a' in 'order clause'


这里的字段a是无法识别的。这里写一段伪代码如下:


select a,b,c
from table_1
where d = 5

union

select a,b,c
from table_1
where e = 8

order by a desc


尽管两个select出的结果列名都是a,b,c,但是最后排序时按照字段a排序,发现报错:说无法识别a字段。

处理办法:上面的排序那一句改为:

order by 1 desc


用你需要的字段的位置索引来定位这个字段,就可以解决了。

这个问题存在于mybatis中,但是直接在数据库中执行时没有问题的。具体原因还不清楚。


举报

相关推荐

0 条评论