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

错误如下:

转载于:https://www.cnblogs.com/loveamyforever/p/7615858.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值