简体   繁体   English

Previous-mysql中的下一个查询

[英]previous - next query in mysql

I have a table in database that is having unique id's. 我在数据库中有一个具有唯一ID的表。 I have a page where one particular id is shown and link is given for next and previous id's. 我有一个页面,其中显示一个特定的ID,并给出了下一个和上一个ID的链接。 I have to get those prev and next id's by one single mysql query .All i have is that particular id on whose data we are currently working on. 我必须通过一个单独的mysql查询来获取这些上一个和下一个ID。我所拥有的就是我们正在处理其数据的特定ID。 id's are not consecutive numbers as sometimes some id's get deleted also.(for eg. 1,2,3,7,9,10,15 etc) ID不是连续的数字,有时某些ID也被删除(例如1,2,3,7,9,10,15等)

So how can i get these two previous and next id's in one single query???? 那么,如何在一个查询中获得这两个上一个和下一个ID?

SELECT
   (SELECT id FROM YourTable WHERE id < YourId ORDER BY id DESC LIMIT 1) AS prev,
   (SELECT id FROM YourTable WHERE id > YourId ORDER BY id ASC LIMIT 1) AS next
;

Replace YourId with the actual id and replace YourTable with valid table name. 用实际的ID替换YourId并用有效的表名替换YourTable。 If any of the values will be NULL then there is no next/prev element to the given. 如果任何值将为NULL则给定没有next / prev元素。

SELECT  *
FROM    (
        SELECT  *
        FROM    mytable
        WHERE   id >= @current
        ORDER BY
                id
        LIMIT 2
        ) q1
UNION ALL
SELECT  *
FROM    (
        SELECT  *
        FROM    mytable
        WHERE   id < @current
        ORDER BY
                id DESC
        LIMIT 1
        ) q2
ORDER BY
        id

May be you try something like - 可能您尝试类似-

SELECT id FROM yourtable where id > '$current_page_id' LIMIT 1 for next 从您的表中选择ID,其中ID>'$ current_page_id'LIMIT 1(下一个)

SELECT id FROM yourtable where id < '$current_page_id' LIMIT 1 for previous 从您的表中选择ID,其中id <'$ current_page_id'LIMIT 1(对于上一个)

you can do it one query as per @RaYell answer. 您可以按照@RaYell答案进行一次查询。

SELECT MAX(id) FROM mytable WHERE id < 11
  • To get the id BEFORE 11 在11之前获取ID

    SELECT MIN(id) FROM mytable WHERE id > 11 从mytable中选择MIN(id),ID> 11

  • To get the id AFTER 11 在11月后获取ID

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM