简体   繁体   中英

How to select the next row in SQL?

i have table in database like:

id  id_tool   tool_last    tool next
1   1         2019-11-01   2020-11-01
2   2         2019-09-15   2020-09-15
3   1         2020-10-30   2021-10-30
4   1         2021-11-02   2022-11-02
5   2         2020-09-10   2021-09-10

I want to get data if id_tool=1 and plan=2020-11-01 then echo actual=2020-10-30

I try with this code:

SELECT tool_last,
       (SELECT id,
               (SELECT id
                FROM t_tabel
                WHERE id_tool='1' AND tool_next='2020-11-01') AS idlast
        FROM t_tabel
        WHERE id > idlast
        ORDER BY id
        LIMIT 1) as idactual
FROM t_tabel
WHERE id = idactual
SELECT t1.*
FROM t_tabel t1
JOIN t_tabel t2 USING (id_tool)
WHERE id_tool = 1
  AND t2.tool_next='2020-11-01'
  AND t1.tool_last > t2.tool_last -- adjust if "next row" needs in another criteria
ORDER BY t1.tool_last LIMIT 1

https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=fb9c3d8c490e4cf0043ae69a4bfe6131

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