欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

MySQL中Union子句不支持order by的解決方法

 更新時間:2016年06月25日 09:32:18   作者:yiluoAK_47  
這篇文章主要介紹了MySQL中Union子句不支持order by的解決方法,結合實例形式分析了在mysql的Union子句中使用order by的方法,需要的朋友可以參考下

本文實例講述了MySQL中Union子句不支持order by的解決方法。分享給大家供大家參考,具體如下:

我對DB知之甚少,這問題只在MySQL遇到,不知道別的DBMS是不是也如此。

問題是這樣的,我打算在一個表里獲得與某一行記錄相鄰的兩行,并且想通過union一起取出來,所以這么寫:

select id,title from subjects where id>#some_id# order by id limit 1
union
select id,title from subjects where id<#some_id# order by id limit 1

但出現(xiàn)了錯誤提示“Incorrect usage of UNION and ORDER BY”。看來不能這么用union和order by,但這里確實是需要order by的。很快,我想到了一個變通的寫法:

select * from (
select id,title from subjects where id>#some_id# order by id limit 1
) union
select id,title from subjects where id<#some_id# order by id limit 1

從經(jīng)驗上說,第二個子句該不會被union影響,可以用order by。于是把第一個子句包在一個括號里,這下應該就可以了。可是還是有錯誤,提示“ Every derived table must have its own alias”。這里的提示是需要給我們括號里面生成的臨時表取一個別名,這個好辦多了。于是改為:

select * from (
select id,title from subjects where id>#some_id# order by id limit 1
) as t1 union
select id,title from subjects where id<#some_id# order by id limit 1

這條語句成功執(zhí)行并且得到了正確的結果,在此寫下來備忘。

更多關于MySQL相關內(nèi)容感興趣的讀者可查看本站專題:《MySQL日志操作技巧大全》、《MySQL事務操作技巧匯總》、《MySQL存儲過程技巧大全》、《MySQL數(shù)據(jù)庫鎖相關技巧匯總》及《MySQL常用函數(shù)大匯總

希望本文所述對大家MySQL數(shù)據(jù)庫計有所幫助。

相關文章

最新評論