MySQL從兩個表中選擇資料並統一排序

來源:互聯網
上載者:User

問題是這樣的,我打算在一個表裡獲得與某一行記錄相鄰的兩行,並且想通過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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.