2

I am having a table name factors. It contains data like this:

id      Name         paretnID
1       abc           0
2       xyz           0
3       abc1          1
4       abc2          1
5       abc3          1
6       qwe           0
7       xyz1          2
8       xyz2          2

I have a set of ids like this: (1,4,7,8)

I want to show all the parent and child ids. Like this

id      name       parentID
1       abc         0
2       xyz         0
4       abc2        1
7       xyz1        2
8       xyz2        2

In my id list 2 is not present but id 2 is the parent of 7 and 8 so it is showing in the result set.

How to write query to show above result?

4

3 回答 3

2
Declare @a table (id  int ,    Name  Varchar(100) ,      parentID int)
Insert into @a
Select 1,'abc',0
UNION Select 2,'xyz',0
UNION Select 3,'abc1',1
UNION Select 4,'abc2',1
UNION Select 5,'abc3',1
UNION Select 6,'qwe',0
UNION Select 7,'xyz1',2
UNION Select 8,'xyz2',2


;WITH Rollups AS (
    SELECT Id, ParentId,Name
    FROM @a Child WHERE ID in (1,4,7,8)
    UNION ALL
    SELECT cl.Id, cl.ParentId, cl.Name
    FROM @a cl 
    INNER JOIN Rollups Children ON Children.ParentID = cl.Id
)
SELECT DISTINCT *
FROM Rollups
Order by ID
于 2013-07-01T10:34:16.123 回答
1

就像是

SELECT 
  id.name,parentid 
FROM 
  factors 
WHERE 
  id IN (1,4,7,8)

UNION

SELECT 
  p.id.p.name,p.parentid 
FROM factors c 
JOIN factors p
ON c.parentid = p.id
WHERE 
  c.id IN (1,4,7,8)
于 2013-07-01T10:23:46.167 回答
0

有同样的问题,用这样的方法解决了......

SELECT b.*
FROM factors AS a
JOIN factors AS b
ON a.parentID = b.id
WHERE a.id IN (1,4,7,8)
于 2018-03-14T09:57:50.550 回答