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語句中查詢出,否則會報錯

錯誤如下:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM