0

在有一个 SQL 表,如:

id, parentid, name 
1     0        Root
2     1        label 1
3     2        label 1.1
4     3        label 1.1.1
5     1        label 2
6     5        label 2.1
7     6        label 2.1.1

现在我想通过 id 2/3/5 等找到所有孩子。我该怎么做?

4

1 回答 1

1

假设table1是您的表名并@input包含输入值

DECLARE @input INT = 2;
DECLARE @parent INT = 0;
DECLARE @name NVARCHAR(200); --same type with name column
SELECT @parent = parentid, @name = name FROM table1 WHERE id = @input;
IF @parent = 0
   SELECT * FROM table1 WHERE id <> @input
ELSE
   SELECT * FROM table1 WHERE name LIKE (@name + '%')

如果名称字段的格式类似于您的示例,则可以这样做。

对于递归 SQL,请以这种方式引用:

WITH temptable (id, parentid, name) AS
(
  SELECT id, parentid, name
  FROM table1 t1
  WHERE t1.id = 1
  UNION ALL
  SELECT t2.id, t2.parentid, t2.name
  FROM table1 t2, temptable t3
  WHERE t2.parentid = t3.id
)
SELECT id, parentid, name 
FROM temptable
WHERE parentid <> 0
于 2012-12-08T05:58:48.837 回答