Select N previous and M next items around current item id

前端 未结 1 598
情深已故
情深已故 2021-01-23 00:45

I have a table with photos

id | year| comm_count
 0   2015         1
 1   2016         2
 2   2017         5
 3   2018         7
 4   2019         1
 5   2020            


        
相关标签:
1条回答
  • 2021-01-23 01:06

    Once you have the year and comm_count values for the selected row with id=7, you can make two simple queries:

    SELECT * FROM photo 
    WHERE year > 2017 AND (comm_count = 1 AND year <= 2022 OR comm_count < 1) 
    ORDER BY comm_count DESC, year DESC LIMIT 3 OFFSET 1
    +----+------+------------+
    | id | year | comm_count |
    +----+------+------------+
    |  6 | 2021 |          1 |
    |  4 | 2019 |          1 |
    +----+------+------------+
    
    SELECT * FROM photo 
    WHERE year > 2017 AND (comm_count = 1 AND year >= 2022 OR comm_count > 1) 
    ORDER BY comm_count ASC, year ASC LIMIT 3 OFFSET 1;
    +----+------+------------+
    | id | year | comm_count |
    +----+------+------------+
    |  3 | 2018 |          7 |
    |  5 | 2020 |          9 |
    +----+------+------------+
    

    If you use MySQL 8.0, you can use the LAG() and LEAD() functions.

    SELECT id, year, 
      LAG(id, 1) OVER w AS next,
      LAG(id, 2) OVER w AS next_next,
      LEAD(id, 1) OVER w AS prev,
      LEAD(id, 2) OVER w AS prev_prev
    FROM photo 
    WHERE year > 2017
    WINDOW w AS (ORDER BY comm_count DESC, year DESC)
    
    +----+------+------+-----------+------+-----------+
    | id | year | next | next_next | prev | prev_prev |
    +----+------+------+-----------+------+-----------+
    |  5 | 2020 | NULL |      NULL |    3 |         7 |
    |  3 | 2018 |    5 |      NULL |    7 |         6 |
    |  7 | 2022 |    3 |         5 |    6 |         4 |
    |  6 | 2021 |    7 |         3 |    4 |      NULL |
    |  4 | 2019 |    6 |         7 | NULL |      NULL |
    +----+------+------+-----------+------+-----------+
    
    0 讨论(0)
提交回复
热议问题