Given a table like this:
| taskId | nextTaskId |
|---|---|
| 1 | 2 |
| 2 | 3 |
| 3 | 6 |
| 4 | 5 |
| 5 | NULL |
| 6 | 7 |
| 7 | 8 |
| 8 | 4 |
I need the following order for output:
| taskId | nextTaskId |
|---|---|
| 1 | 2 |
| 2 | 3 |
| 3 | 6 |
| 6 | 7 |
| 7 | 8 |
| 8 | 4 |
| 4 | 5 |
| 5 | NULL |
Is there any way to do this via MySQL query?
Given a table like this:
| taskId | nextTaskId |
|---|---|
| 1 | 2 |
| 2 | 3 |
| 3 | 6 |
| 4 | 5 |
| 5 | NULL |
| 6 | 7 |
| 7 | 8 |
| 8 | 4 |
I need the following order for output:
| taskId | nextTaskId |
|---|---|
| 1 | 2 |
| 2 | 3 |
| 3 | 6 |
| 6 | 7 |
| 7 | 8 |
| 8 | 4 |
| 4 | 5 |
| 5 | NULL |
Is there any way to do this via MySQL query?
Using recursive CTE -
WITH RECURSIVE
self_ref_cte ( taskid, nexttaskid )
AS
( SELECT taskid, nexttaskid
FROM self_ref WHERE taskid = 1
UNION ALL
SELECT s.taskid, s.nexttaskid
FROM self_ref_cte c JOIN self_ref s
ON s.taskid = c.nexttaskid
)
SELECT * FROM self_ref_cte;
DB fiddle here.