doujiongqin0687 2013-07-07 07:28
浏览 50
已采纳

组合多个mysql查询以将结果作为单行获取

This is my table : question

id   | name
-----+-----
 2   | name 1
 3   | name 2 
 4   | name 3
 5   | name 4
 10  | name 5 
 20  | name 6
 21  | name 7

I have an id say 5, I need to get the previous and next rows, so if id is 5 I need to get 4, 5 and 10

Now I am using these queries

select * from question where id = (select max(id) from question where id < 5);
select * from question where id = (select min(id) from question where id > 5);

What I am looking is for a single query (if its possible). Some thing like

SELECT xx AS prevId, id, yy AS nextId FROM questions WHERE .......

If there is not previous id or next id it should be 0 or -1

For example
id: 5
Return : 4, 5, 10

id:2
Return : -1, 2, 3

id: 21
Return 20, 21, -1

I know how to do this with multiple queries and with some if conditions in PHP, but I am looking for a pure mySQL approach if its possible.

  • 写回答

2条回答 默认 最新

  • dttwois6098 2013-07-07 08:27
    关注

    Here are few examples, someone else can tell which one is more efficient.

    Query 1

    Select
      (select id from question where id<5 order by id desc limit 0,1) as prevId,
      id,
      (select id from question where id>5 order by id asc limit 0,1) as nextId
    From question
    Where id=5;
    

    Query 2

    Select
      (select max(id) from question where id<5) as prevId,
      id,
      (select min(id) from question where id>5) as nextId
    From question 
    Where id=5;
    

    Ah, did not see -1 definition, needs some more hacking. Coalesce function takes 1..n arguments and returns first nonnull value.

    Query 3

    Select
      Coalesce( (select max(id) from question where id<21), -1) as prevId,
      id,
      Coalesce( (select min(id) from question where id>21), -1) as nextId
    From question
    Where id=21;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料