如何让父母的所有子女

时间:2019-05-28 13:10:13

标签: sql sql-server tsql

我要从一张桌子中拿走所有包含肉类的东西。将来可以创建其他元素(子ID)到组(父ID),例如现在的食物->肉->动物肉->猪。将来有人可以像这样的食物->肉类->动物肉->猪->培根来创建另一个具有父母ID的记录,下一个人可以与父母ID培根等创建另一个记录。 我该如何查询其所有父元素为MEATS的元素?因此查询应返回元素猪,牛,培根。

+---------+----------+--------------+
| childId | parentId | name         |
+---------+----------+--------------+
| 1       | 0        | FOOD         |
+---------+----------+--------------+
| 2       | 1        | FRUITS       |
+---------+----------+--------------+
| 3       | 1        | VEGETABLES   |
+---------+----------+--------------+
| 4       | 1        | MEATS        |
+---------+----------+--------------+
| 5       | 2        | apple        |
+---------+----------+--------------+
| 6       | 2        | banana       |
+---------+----------+--------------+
| 7       | 3        | carrot       |
+---------+----------+--------------+
| 8       | 3        | tomatoes     |
+---------+----------+--------------+
| 9       | 4        | FISH MEATS   |
+---------+----------+--------------+
| 10      | 4        | ANIMAL MEATS |
+---------+----------+--------------+
| 11      | 9        | cod          |
+---------+----------+--------------+
| 12      | 9        | salmon       |
+---------+----------+--------------+
| 13      | 10       | cow          |
+---------+----------+--------------+
| 14      | 10       | pig          |
+---------+----------+--------------+

1 个答案:

答案 0 :(得分:0)

递归CTE(公用表表达式)将完成此任务:

with
x as (
  select childId, parentId, name from t where id = 3
  union all
  select t.childId, t.parentId, t.name
  from x
  join t on t.parentId = x.childId
)
select * from x