2

这里有很多关于选择使用 ID 来解决问题的匹配行的周围行的问题。这不是我需要的,因为我的表是单词,我需要按单词排序。

示例表:字

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

这显然是行不通的。

4

2 回答 2

9
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小提琴在这里

于 2012-09-06T05:03:14.680 回答
2

Try deriving a RANK for the ordered column set. Something like this will work:

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;

Hope this helps!

于 2012-09-06T05:21:52.900 回答