![](/img/trans.png)
[英]SQL Server: How to get all child records given a parent id in a self referencing table
[英]How to get all child of a given id in SQL Server query
我在SQL Server数据库中有两个表:
category(
itemid,
parentid
)
ArticleAssignedCategories(
categid,
artid
)
categid
是itemid
的外键
我想要得到的计数artids
给定的是和儿童itemid
(孩子意味着类别parentid
给出itemid
。)
例如; 如果给定itemid = 1
并且在表category
具有(3,1),(4,1)(5,3)
3、4、5都是1的孩子
谁能帮我写一个好的查询?
可以使用CTE进行递归查询
with CTE(itemid, parentid)
as (
-- start with some category
select itemid, parentid
from category where itemid = <some_itemid>
union all
-- recursively add children
select c.itemid, c.parentid
from category c
join CTE on c.parentid = CTE.itemid
)
select count(*)
from ArticleAssignedCategories a
join CTE on CTE.itemid = a.categid
这是查询。 希望对您有帮助
select b.artid,count(b.artid) from category a
inner join ArticleAssignedCategories b on a.itemid = b.artid
group by b.artid
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.