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语句中查询出,否则会报错

    错误如下:

  • 相关阅读:
    线程的终止pthread_exit和返回为什么终止的原因
    临界区互斥使用之使用自旋锁
    临界区的同步操作-------------使用信号量 实现
    常用解压操作
    group compare vs pair compare
    两个总体的参数关系
    纳伪|去真
    Ho|H1|p-value|p值与U值|单侧检验
    统计分布近似转化
    样本均值的标准误差|样本均值的标准差|总体标准差|样本标准差|简单随机抽样|样本均值估计|样本方差估计|
  • 原文地址:https://www.cnblogs.com/loveamyforever/p/7615858.html
Copyright © 2011-2022 走看看