看板 Database 關於我們 聯絡資訊
※ 引述《JYHuang (夏天到了,冷不起來了說)》之銘言: : 再將starjou兄的語法做延伸 : 選出table中指定 id 值和其上下一筆的資料 : SELECT A.id FROM news AS A LEFT JOIN : (SELECT id FROM news WHERE id >= : (select IFNULL(max(id),10) from news where id <10 ) : ORDER BY id LIMIT 3) AS B : ON A.id = B.id WHERE B.id IS NULL : 在一個有16筆資料的資料表中查詢 : 花費0.0005 秒(一般查詢 約0.0003 sec) 其實解法很簡單耶@@: 假設你的目標id是Q (某數字) 則: 1、選出Q及Q的上一筆和下一筆資料: select * from news where ABS(id-Q)<=1 2、選出Q及其上下一筆「以外」的資料: select * from news where ABS(id-Q)>1 3、選出Q及其下一筆「以外」的資料: select * from news where id<Q or id>(Q+1) 4、選出Q及其上一筆「以外」的資料: select * from news where id>Q or id<(Q-1) 都是一行解決… ps. ABS函數就是取其絕對值... -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 118.166.139.138
JYHuang:當id有間斷時,就不行了吧? 06/25 22:13
diamondking:如果不連續,Oracle有rownum,mysql看來真的沒有簡單的 06/25 22:20
chph:SELECT id FROM news WHERE id < N ORDER BY id DESC LIMIT 1 06/25 22:53
chph:改個條件與排序, 再union all 這樣呢? 推文等好久.. 囧 06/25 22:57
diamondking:這版推文要等2xx秒實在是太扯了= = 06/26 00:05
starjou:推完一句可以去唸幾遍大悲咒再回來 06/26 00:10