1. 程式人生 > >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

但出現了錯誤提示“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

從經驗上說,第二個子句該不會被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

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

關於別名用法請參考w3schoolhttp://www.w3school.com.cn/sql/sql_alias.asp