本文实例讲述了mysql中union子句不支持order by的解决方法。分享给大家供大家参考,具体如下:
我对DB知之甚少,这问题只在mysql遇到,不知道别的DBMS是不是也如此。
问题是这样的,我打算在一个表里获得与某一行记录相邻的两行,并且想通过union一起取出来,所以这么写:
select id,title from subjects where id>#some_id# order by id limit 1 union select id,title from subjects where id <p>但出现了错误提示“<span style="color: #0000ff">Incorrect usage of UNION and ORDER BY</span>”。看来不能这么用union和order by,但这里确实是需要order by的。很快,我想到了一个变通的写法:</p> <p> </p><pre class="prebrush"> select * from ( select id,title from subjects where id>#some_id# order by id limit 1 ) union select id,title from subjects where id <p>从经验上说,第二个子句该不会被union影响,可以用order by。于是把第一个子句包在一个括号里,这下应该就可以了。可是还是有错误,提示“ Every derived table must have its own alias”。这里的提示是需要给我们括号里面生成的临时表取一个别名,这个好办多了。于是改为:</p> <p> </p><pre class="prebrush"> select * from ( select id,title from subjects where id>#some_id# order by id limit 1 ) as t1 union select id,title from subjects where id <p>这条语句成功执行并且得到了正确的结果,在此写下来备忘。</p> <p>更多关于MySQL相关内容感兴趣的读者可查看本站专题:《MySQL日志操作技巧大全》、《MySQL事务操作技巧汇总》、《MySQL存储过程技巧大全》、《MySQL数据库锁相关技巧汇总》及《MySQL常用函数大汇总》</p> <p>希望本文所述对大家MySQL数据库计有所帮助。</p>
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END