简体   繁体   中英

SQL query to find multi level hierarchical data

Imagine I have some data in a relational table like below.

name           friend_name 

Ryan           James 
Chin           James 
Jack           Charley
Tomy           Ryan
Bill           Chin

Now, given friend_name 'James' I want the result as

name 

Ryan 
Chin 
Tomy
Bill

What should my SQL query look like? I'm using SQL Server.

You can use a recursive CTE to find all the friends of friends of James :

WITH CTE AS (
  SELECT *
  FROM friends
  WHERE friend_name = 'James'
  UNION ALL
  SELECT f.*
  FROM friends f
  JOIN CTE ON f.friend_name = CTE.name
)
SELECT name
FROM CTE

Output:

name
Ryan
Chin
Bill
Tomy

Demo on SQLFiddle

The entry level way to do this would just be a UNION if you don't have duplicates.

SELECT name
FROM t1
WHERE friend_name = 'James'

UNION

SELECT friend_name name
FROM t2
WHERE name = 'James'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM