zoukankan      html  css  js  c++  java
  • 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语句中查询出,否则会报错

    错误如下:

  • 相关阅读:
    阿里巴巴2018秋招面经之前端岗(1~5面)
    面试分享:2018阿里巴巴前端面试总结(题目+答案 30题)
    2018年各大互联网前端面试题三(阿里)
    阿里巴巴2016前端工程师面试题
    2016 阿里校招笔试前端题目,你还记得吗?
    2018阿里前端校招分享(笔试篇)
    2017 阿里校招前端笔试题小结
    阿里2018校招编程题
    ko.js学习一
    简单的3d变换
  • 原文地址:https://www.cnblogs.com/loveamyforever/p/7615858.html
Copyright © 2011-2022 走看看