を取得する方法は、コード
WITH cte AS (
SELECT
t1.name AS anchor_name
, t1.type AS type
, t2.parent
, 0 AS level
FROM #T1 t1 JOIN #T2 t2 ON t1.type = t2.type
UNION ALL
SELECT cte.anchor_name, cte.type, t2.parent, cte.level+1
FROM cte JOIN #T2 t2 ON cte.parent = t2.type
)
, tmp AS (
SELECT anchor_name, MAX(cte.level) AS max_level
FROM cte
GROUP BY cte.anchor_name
)
SELECT cte.anchor_name as name, cte.type
FROM tmp JOIN cte ON cte.anchor_name = tmp.anchor_name AND cte.level = tmp.max_level
がされ、これはテストコードです:あなたが必要
CREATE TABLE #T1 (
name VARCHAR(2)
, type VARCHAR(MAX)
);
CREATE TABLE #T2 (
type VARCHAR(MAX)
, parent VARCHAR(MAX)
);
INSERT INTO #T1 (name, type)
VALUES
('a1', 'artist')
,('a1', 'person')
,('a2', 'person')
,('a2', 'athlete')
,('a3', 'person')
,('a3', 'artist')
,('a3', 'actor');
INSERT INTO #T2 (type, parent)
VALUES
('artist' , 'person')
,('actor' , 'artist')
,('athlete' , 'person')
,('person' , '');
SELECT *
FROM #T1;
SELECT *
FROM #T2;
WITH cte AS (
SELECT
t1.name AS anchor_name
, t1.type AS type
, t2.parent
, 0 AS level
FROM #T1 t1 JOIN #T2 t2 ON t1.type = t2.type
UNION ALL
SELECT cte.anchor_name, cte.type, t2.parent, cte.level+1
FROM cte JOIN #T2 t2 ON cte.parent = t2.type
)
, tmp AS (
SELECT anchor_name, MAX(cte.level) AS max_level
FROM cte
GROUP BY cte.anchor_name
)
SELECT cte.anchor_name as name, cte.type
FROM tmp JOIN cte ON cte.anchor_name = tmp.anchor_name AND cte.level = tmp.max_level
http://rextester.com/TRD23741
一番遠いノードが何を意味するのかを明確に説明します。 – DVT
ちょうど質問を書き直しました。これは少し鮮明であることを願っています。 – user1848018
mysqlまたはsql-serverですか?あなたの質問には両方のタグが付きます。 –