0

假设我有这张桌子

-----------------
|  id   |   word |
|  5    |   aab  |
|  6    |   sea  |
|  7    |   blue |
|  8    | color  |
|  9    |  nn    |
|  10   |  pp    |
|  11   |  oo    |
|  12   |  qq    |

一个人访问了它所在的id页面8

我要显示的是在此之前和之后的两个结果id。这两个结果是按字母顺序排列的,所以在命令中我应该得到:

aab - blue - color - nn - oo 

我怎样才能在mysql查询中做到这一点?我正在寻找最有效的代码。我需要运行多少个查询?我怎样才能在我的 id 之前按字母顺序得到结果,并且每边只得到两个。请帮忙。

4

2 回答 2

3

你可以用limitand做到这一点union all

select word
from ((select *
       from t
       where word<= (select word from t where id = 8)
       order by word desc
       limit 3
      ) union all
      (select *
       from t
       where word> (select word from t where id = 8)
       order by word
       limit 2
      )
     ) t
order by word;
于 2013-06-17T16:01:00.450 回答
0

您应该创建该表的排序版本。然后,当给定一个 ID 时,您可以对 ID 进行算术运算。

/* How to create the sorted table */
create table sorted_words 
(new_id mediumint not null auto_increment, primary key (new_id))
as select id as old_id, word from words order by word asc;

/* Query for getting two above and two under */
select id, word from sorted where id between 6 and 10

工作小提琴:http ://sqlfiddle.com/#!2/c6734/1

于 2013-06-17T16:03:52.180 回答