union 和order by 使用时排序不正确

Posted Amy-WebFrontEnd

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了union 和order by 使用时排序不正确相关的知识,希望对你有一定的参考价值。

静态专题和APP版专题(order by不起作用):
[query]
sql=
(select sp_f13577,sp_f13576 from sp_t113 where url_1 not like \'%index.shtml\' and sp_f24507=\'1\' and deleted=\'n\' and createdate>FROM_DAYS(TO_DAYS(CURDATE())-500) order by createdate desc,createtime desc)
union all
(select sp_f11673,d_id from show_page_2008 where (sp_f16719=\'no\' and sp_f16719 is not null) and sp_f24508=\'1\' and deleted=\'n\' and createdate>FROM_DAYS(TO_DAYS(CURDATE())-500) or d_id=\'1872\' order by sp_f16945 desc,createdate desc)

  mysql 语句如上,而结果最新创建的稿件排到了最下方

 参考:

http://blog.sina.com.cn/s/blog_7c983ca601011mak.html

查阅资料后mysql修改如下:

[query]
sql=
(select * from (
select sp_f11673,d_id from show_page_2008 where (sp_f16719=\'no\' and sp_f16719 is not null) and sp_f24508=\'1\' and deleted=\'n\' and createdate>FROM_DAYS(TO_DAYS(CURDATE())-500) or d_id=\'1872\' order by sp_f16945 desc,createdate desc
)
as table1
)
union
(select * from (
select sp_f13577,sp_f13576 from sp_t113 where url_1 not like \'%index.shtml\' and sp_f24507=\'1\' and deleted=\'n\' and createdate>FROM_DAYS(TO_DAYS(CURDATE())-500) order by createdate desc,createtime desc
)
as table2
)

 结果可正常显示:

 以上mysql代码实现了 两个表内部进行排序后再连接到一起

遇到的问题:Every derived table must have its own alias

解决方法:进行嵌套查询的时候子查询出来的的结果是作为一个派生表来进行上一级的查询的,所以子查询的结果必须要有一个别名

 

参考:http://blog.sina.com.cn/s/blog_5d2eee260100xu8b.html

那如何实现两个表数据整合后再整体排序(先union后order by)呢?解决方法如下:

静态专题和APP版专题(两表连接后再排序显示):
[query]
sql=
(select sp_f11673,d_id,createdate,createtime from show_page_2008 where (sp_f16719=\'no\' and sp_f16719 is not null) and sp_f24508=\'1\' and deleted=\'n\' and createdate>FROM_DAYS(TO_DAYS(CURDATE())-500) or d_id=\'1872\')
union
(select sp_f13577,sp_f13576,createdate,createtime from sp_t113 where url_1 not like \'%index.shtml\' and sp_f24507=\'1\' and deleted=\'n\' and createdate>FROM_DAYS(TO_DAYS(CURDATE())-500))
order by createdate desc,createtime desc

注意:此处order by 处的字段必须在select语句中查询出,否则会报错

错误如下:

以上是关于union 和order by 使用时排序不正确的主要内容,如果未能解决你的问题,请参考以下文章

UNION、TOP、ORDER BY联合使用时处理顺序是啥?

ORACLE 两个order by的SQL使用 UNION 或者 UNION ALL 报错 ORA-00933:sql命令未正确结束

使用UNION后,ORDER BY 怎样使用

UNION ALL、UNION与ORDER BY

如何使用 SQLite 使用 UNION ALL 和 ORDER BY 进行排序

为啥在mysql中第一个union两个子句的order by不起作用