如何从子ID中选择父ID

时间:2013-07-01 10:17:13

标签: sql-server

我有一个表名factors。它包含这样的数据:

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

我有一组这样的ID:(1,4,7,8)

我想显示所有父级和子级ID。 喜欢这个

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

在我的ID列表中2不存在,但ID 278的父级,因此它显示在结果集中。

如何编写查询以显示上述结果?

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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)

答案 2 :(得分:0)

遇到同样的问题,用这样的东西解决了......

SELECT b.*
FROM factors AS a
JOIN factors AS b
ON a.parentID = b.id
WHERE a.id IN (1,4,7,8)