2

我有一个按字母顺序排列的查询

select id, color_name from colors order by color_name

输出

| 4 | 蓝色的
| 1 | 红色的
| 2 | 紫色
| 3 | 黄色

我想查询特定记录的前后记录。示例:红色

所需的输出:

| 4 | 蓝色的
| 1 | 红色的
| 2 | 紫色

谢谢。

4

3 回答 3

5

尝试使用 UNION:

SELECT  A.id, A.color_name FROM  (
   (
      SELECT  id, color_name FROM colors
      WHERE color_name <= 'red'
      ORDER BY color_name DESC
      LIMIT 2
   )
  UNION
   (
      SELECT id, color_name FROM colors
      WHERE color_name > 'red'
      ORDER BY color_name ASC
      LIMIT 1
   )

 ) as A
ORDER BY A.color_name
于 2012-07-26T04:11:05.260 回答
3

您可以使用变量对结果集进行排名,然后将相同的结果集连接到其自身,其中颜色名称为红色且排名编号在“红色”排名的 1 个位置内:

SELECT b.id, b.color_name
FROM
(
    SELECT a.*, @rn:=@rn+1 AS rn 
    FROM colors a
    CROSS JOIN (SELECT @rn:=0) AS var_init
    ORDER BY a.color_name
) a
INNER JOIN
(
    SELECT a.*, @rn2:=@rn2+1 AS rn 
    FROM colors a
    CROSS JOIN (SELECT @rn2:=0) AS var_init
    ORDER BY a.color_name
) b ON a.color_name = 'red' AND a.rn IN (b.rn-1, b.rn, b.rn+1)

如果您碰巧正在搜索位于列表开头或结尾的颜色,那么当然只会显示两个结果。


在SQLFiddle上查看演示

于 2012-07-26T04:47:00.927 回答
1
select id, color_name from (
          select rowno, id, color_name from (
              select @rownum:=@rownum+1 rowno, id, color_name from 
                  colors, (select @rownum:=0) t1 
              order  by color_name
          ) t2
where rowno in (@row:=( 
          select rowno from (
              select @rownum:=@rownum+1 rowno, color_name 
              from colors, (
                        select @rownum:=0) t3 
              order  by color_name
              ) t4 
          where color_name = "red"), @row + 1, @row -1 )) t5
于 2012-07-26T05:36:05.670 回答