Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql server 如何从子id中选择父id_Sql Server - Fatal编程技术网

Sql server 如何从子id中选择父id

Sql server 如何从子id中选择父id,sql-server,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 我有一组

我有一个表名
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。 像这样

id      name       parentID
1       abc         0
2       xyz         0
4       abc2        1
7       xyz1        2
8       xyz2        2
在我的id列表中,
2
不存在,但id
2
7
8
的父项,因此它显示在结果集中

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

类似

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)

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

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

为什么
3
5
6
不在结果中?@ypercube据我所知,他希望所有节点都在(1,4,7,8)中,所需的父节点右@bummi,你是right@bummi是的,我没有读过“我有一组这样的ID(1,4,7,8)”,这是一个以
开头的查询;使用
并以Order by ID@结尾,a将是您的表格。如果你的树有两个以上的级别,如果不使用CTE,你将不会得到想要的结果。非常感谢你的解决方案
SELECT b.*
FROM factors AS a
JOIN factors AS b
ON a.parentID = b.id
WHERE a.id IN (1,4,7,8)