SQL Query: Fetch ordered rows from a table - II

孤街醉人 提交于 2019-12-25 03:46:32

问题


Following are some entries from a table:

id      r_id        a_id        p_id

1 9 9 0 2 9 105 108 3 9 102 9 4 9 106 105 5 9 108 102 6 10 10 0 7 10 15 18 8 10 12 10 9 10 16 15 10 10 18 12

I'm looking for an SQL query that will give an output like:

1       9           9           0
3       9           102         9
5       9           108         102
2       9           105         108
4       9           106         105
6       10           10          0
8       10           12         10
10      10           18         12
7       10           15         18
9       10           16         15

Well, I asked a similar question here but the question was not complete and I also got few excellent answers. Editing that question might make the answers unacceptable, so I did not edit and added this as a new question here.

  • The root item has a p_id = 0
  • For one r_id there can only be one p_id = 0
  • The table shown on which Query need to be run may not be sorted with respect to root.
  • I'm looking things to work in PostgreSql

EDIT: The idea is to sort the rows in such a way that a row with {r_id, p_id} = x should come below the row with {r_id, a_id} = x.


回答1:


Modifying the answer to your previous question, gives the following...

WITH RECURSIVE sub(s_id, s_r_id, s_a_id, s_p_id, row) AS (
    SELECT id, r_id, a_id, p_id, 1 AS row FROM foo WHERE p_id = 0
UNION ALL
    SELECT id, r_id, a_id, p_id, (row + 1)  FROM foo JOIN sub ON s_a_id = p_id AND s_r_id = r_id
)
SELECT * FROM sub ORDER BY s_r_id, row;



回答2:


Just change the ORDER BY:

WITH RECURSIVE sub(s_id, s_r_id, s_a_id, s_p_id, row) AS (
    SELECT id, r_id, a_id, p_id, 1 AS row FROM foo WHERE p_id = 0
UNION ALL
    SELECT id, r_id, a_id, p_id, (row + 1)  FROM foo JOIN sub ON s_a_id = p_id
)
SELECT * FROM sub
ORDER BY s_r_id ASC, row ASC
;


来源:https://stackoverflow.com/questions/6041836/sql-query-fetch-ordered-rows-from-a-table-ii

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!