以下是表格中的一些条目:
id r_id a_id p_id1 9 9 0 2 9 105 108 3 9 102 9 4 9 106 105 5 9 108 102
是否可以使用SQL查询获取以下输出
1 9 9 0 3 9 102 9 5 9 108 102 2 9 105 108 4 9 106 105
我们的想法是对行进行排序,使得p_id = x的行应该位于a_id = x的行下方。
我希望问题有道理。
的问候,
Mayank
编辑:
我正在寻找PostgreSql
答案 0 :(得分:1)
以下内容改编自有效的SQL Server 2005解决方案。
我做了一些假设
p_id = 0
SQL声明
;WITH RECURSIVE q AS (
SELECT *
, 1 AS Level
FROM ATable
WHERE p_id = 0
UNION ALL
SELECT t.*
, Level = Level + 1
FROM q
INNER JOIN ATable t ON t.p_id = q.a_id
)
SELECT *
FROM q
ORDER BY
Level
答案 1 :(得分:1)
使用递归查询(PostgreSQL版本8.4或更高版本):
/* test data:
CREATE TABLE foo (id, r_id, a_id, p_id) AS
SELECT 1,9,9,0
UNION ALL SELECT 2,9,105,108
UNION ALL SELECT 3,9,102,9
UNION ALL SELECT 4,9,106,105
UNION ALL SELECT 5,9,108,102
;
*/
-- the query you need:
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 row;