如何在有一个孩子的两个父母之间建立联系

时间:2017-08-24 15:33:48

标签: sql oracle

我已经陷入这个问题几个小时了。

如您所见, D_ID 8有两个 root_id (3,6)。问题是如何建立3&的关系。 6,最终所有 root_id 6应该被3替换。 我认为有一种更简单的方法可以使用Python或R来解决它。不幸的是,我对这些并不熟悉。

任何人都可以帮忙吗?任何想法将不胜感激。

代码例如:

WITH device
AS 
(
SELECT 1 AS d_id, 'D1' AS dname FROM dual
UNION ALL
SELECT 2 AS d_id, 'D2' AS dname FROM dual
UNION ALL
SELECT 3 AS d_id, 'D3' AS dname FROM dual
UNION ALL
SELECT 4 AS d_id, 'D4' AS dname FROM dual
UNION ALL
SELECT 5 AS d_id, 'D5' AS dname FROM dual
UNION ALL
SELECT 6 AS d_id, 'D6' AS dname FROM dual
UNION ALL
SELECT 7 AS d_id, 'D7' AS dname FROM dual
UNION ALL
SELECT 8 AS d_id, 'D8' AS dname FROM dual
UNION ALL
SELECT 9 AS d_id, 'D9' AS dname FROM dual
UNION ALL
SELECT 10 AS d_id, 'D10' AS dname FROM dual
)
, connection
AS
(
SELECT 1 AS p_id, 2 AS c_id FROM dual
UNION ALL
SELECT 3 AS p_id, 4 AS c_id FROM dual
UNION ALL
SELECT 4 AS p_id, 5 AS c_id FROM dual
UNION ALL
SELECT 6 AS p_id, 7 AS c_id FROM dual
UNION ALL
SELECT 7 AS p_id, 8 AS c_id FROM dual
UNION ALL
SELECT 4 AS p_id, 8 AS c_id FROM dual
UNION ALL
SELECT 5 AS p_id, 9 AS c_id FROM dual
)
SELECT d.d_id, d.dname, connect_by_root(d_id) rootdeviceid, substr(sYS_CONNECT_BY_PATH(d_id, '>') ,2) AS path
  FROM device D
LEFT JOIN connection c ON (d.d_id = c.c_id)
CONNECT BY prior d.d_id = c.p_id
START WITH C.p_id IS NULL
ORDER BY d.d_id

我希望现在应该更清楚一点。 enter image description here

0 个答案:

没有答案