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条)

报告相同问题?

悬赏问题

  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流
  • ¥15 Rstudio 保存代码闪退
  • ¥20 win系统的PYQT程序生成的数据如何放入云服务器阿里云window版?