MySQL - select one row - then one next and one previous relative to the selected

依然范特西╮ 提交于 2019-12-04 08:24:22

The simplest way to do this is to exploit the fact that, although not continuous, your ids are in ascending order.

For example:

SELECT * FROM Table WHERE id = 8

UNION
--Select the first item less than 8
SELECT * FROM Table WHERE id = (SELECT MAX(id) FROM Table WHERE id < 8)

UNION
--select the first item greater than 8
SELECT * FROM Table WHERE id = (SELECT MIN(id) FROM Table WHERE id > 8)

If you only know the string, then:

DECLARE _id INT

SELECT _id = id FROM Table WHERE value = 'i_like_women'

Then you can simply feed this _id into the above query, instead of 8.

Note you don't need to use ` to demarcate the table and column names.

Ramiz Raja

Here is the query which will return all three records.

SELECT * 
FROM `TABLE` 
WHERE id >= (
    SELECT id 
    FROM `TABLE` 
    WHERE id < (SELECT id FROM `TABLE` WHERE name = 'i_like_women')
    ORDER BY id DESC 
    LIMIT 1
)
ORDER BY id ASC
LIMIT 3

The one before can be retrieved with:

SELECT `value` 
FROM `TABLE` 
WHERE id < (SELECT id FROM `TABLE` WHERE name = 'i_like_women')
ORDER BY id DESC
LIMIT 1

You can do the opposite query to find the next one

this query is working fine on first and last record as well

SELECT * FROM `products` WHERE `ProductId`  = (SELECT MAX(ProductId) FROM `products`  WHERE ProductId < 1)  AND SubCategoryId=1


UNION

SELECT * FROM `products` WHERE `ProductId`  = (SELECT MIN(ProductId) FROM `products`  WHERE ProductId > 1)  AND SubCategoryId=1


UNION

SELECT * FROM `products` WHERE `ProductId`  = (SELECT MIN(ProductId) FROM `products`  WHERE ProductId < 1)  AND SubCategoryId=1 


UNION

SELECT * FROM `products` WHERE `ProductId`  = (SELECT MAX(ProductId) FROM `products`  WHERE ProductId > 1)  AND SubCategoryId=1


ORDER BY ProductId ASC

i Hope this will solve your Problem :)

Neeraj Rathod

I have found better and easy answer for the below question(finding next and previous row ),

$neighbors = $this->WorkDescription->find('neighbors',array('field' => 'id', 'value' => 3));

it will gives output like this-

Array
(
    [prev] => Array
        (
            [WorkDescription] => Array
                (
                    [id] => 1
                    [title] => Twenty
                    [ter_id] => 1
                    [cat_id] => 4    
                    [writer] => abk
                    [director] => Dir
                    [producer] => pro   
               )
        )

    [next] => Array
        (
            [WorkDescription] => Array
                (
                    [id] => 3
                    [title] => The Piper
                    [ter_id] => 1
                    [cat_id] => 3        
                    [writer] => abk
                    [director] => Dir
                    [producer] => pro
                )
           )
)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!