简体   繁体   中英

MYSQL sorting and limit using a certain row and selecting previous and next rows

I have a simple table called users with the following data:

id | hops
 1 | 3
 2 | 1
 3 | 5
 4 | 2
 5 | 4
 6 | 5

I want to select the number of hops of any given id that I specify and also select the next and previous ids according to the number of hops sorted from highest to lowest.

To explain more I use the following query:

SELECT * FROM test WHERE id = 1 
OR (id > 1 AND hops >= (SELECT hops FROM test WHERE id= 1) ) 
OR (id < 1 AND hops <= (SELECT hops FROM test WHERE id= 1) ) 
LIMIT 3

So in the above query I tried to get id=1 , next id with the same or higher number of hops, and the previous id with the same or lower number of hops.

This is the result i get:

id | hops
1  | 3
3  | 5
5  | 4

As you can see it selected id=1 and two higher ids although I want only one higher id and one lower id. So, in this case the result should be like this instead:

id | hops
1  | 3
3  | 5

As there is no lower id than 1, so nothing lower to fit the criteria and selects only 1 higher id. The wrong result is because of using LIMIT 3 but I can't use a LIMIT for each condition. So don't know how to approach this at all.

Have another question, would using the sub-query "SELECT hops FROM test WHERE id= 1" slow down the server on a large scale?? I heard that it's not preferable to use sub-queries but have no other way to get this number except using a separate query.

Thanks

here you go, change the order by ID according to your liking...you didn't say if you wanted the closest number of hops or the closest ID, just one greater or lower

SELECT * FROM test 
WHERE id IN (1,(
    SELECT id FROM test WHERE id > 1 AND hops >= (
        SELECT hops FROM test WHERE id = 1
        ) ORDER BY id LIMIT 1
    ), (
    SELECT id FROM test WHERE id < 1 AND hops <= (
        SELECT hops FROM test WHERE id = 1
        ) ORDER BY id DESC LIMIT 1
))

If I understand your question correctly, I believe the following will work.

-- Previous Rec
SELECT  t2.*
FROM    test as t1
        JOIN test as t2 ON t2.hop <= t1.id
WHERE   t1.id = 1
ORDER BY t2.id DESC
LIMIT 1

UNION ALL

-- Current Rec
SELECT  *
FROM    test as t
WHERE   id = 1

UNION ALL

-- Following Rec
SELECT  t2.*
FROM    test as t1
        JOIN test as t2 ON t2.id >= t1.hop
WHERE   t1.id = 1
ORDER BY t2.id ASC
LIMIT 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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