简体   繁体   中英

MySQL: Getting adjacent rows of value in indexed column in table

I've a table ALL_VALUES having single column VALUE which is indexed.

VALUE
3
6
10
11
17
18
18
21
25
25
29

Now if I know a particular value say 17, I like to fetch rows that include 17 and top and bottom adjacent 3 rows ie 6, 10, 11, 17, 18, 18, 21.

How shall I write SELECT query for this.

Sorry, I'm used to MSSQL. But I think this might work:

  Select t1.value from((SELECT value
    FROM ALL_VALUES
    WHERE value <= 17
    ORDER BY value DESC
    LIMIT 4)

    UNION ALL

    (SELECT value
    FROM ALL_VALUES
    WHERE value > 17
    LIMIT 3)) t1 order by value ASC;

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