这里有很多关于选择匹配行的周围行的问题,这些行使用ID来完成这个技巧。这不是我需要的,因为我的桌子是单词,我需要用文字排序。
示例表:Word
id word
1 boing
2 aleluya
3 chimp
4 dinner
5 after
6 zup
7 pop
8 house
9 chain
假设我希望通过单词ASC排序的3个周围的“晚餐”行,我的结果应该是:
id word
1 boing
9 chain
3 chimp
4 dinner
8 house
7 pop
6 zup
我需要使用什么查询?我试过这个:
SELECT word FROM `word` t WHERE t.word <> 'dinner'
ORDER BY abs( t.word - (SELECT t2.word FROM word t2 WHERE t2.word = 'dinner'))
LIMIT 5
显然不起作用。
答案 0 :(得分:8)
SELECT t.id, t.word FROM word t
WHERE t.word >=
(
SELECT lo.word FROM `word` lo
WHERE lo.word <= 'dinner' ORDER BY lo.word DESC LIMIT 3,1
)
ORDER BY t.word ASC LIMIT 0,7
;
SQL小提琴here
答案 1 :(得分:2)
尝试为有序列集导出RANK。这样的事情会起作用:
SELECT
e.id, e.word
FROM
(select id, word, @rownum:=@rownum+1 AS RANK from Word, (select @rownum := 0) r order by word asc) d, -- for getting the rank for 'dinner'
(select id, word, @num:=@num+1 AS RANK from Word, (select @num := 0) r order by word asc) e -- for getting the rank for the other words
WHERE
d.word='dinner' AND
e.RANK BETWEEN d.RANK-3 AND d.RANK+3 -- +/- 3 columns;
希望这有帮助!