0

I have two tables in SQL Server database:

category( 
   itemid, 
   parentid
)

ArticleAssignedCategories(
   categid, 
   artid
)

categid is a foreign key of itemid

I want to get count of artids and child of that for given itemid (child means categories with parentid of given itemid.)

For example; If given itemid = 1 and in table category have (3,1),(4,1)(5,3)

All of 3, 4, 5 are child of 1

Can anyone help me to write a good query?

4

2 回答 2

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
于 2013-08-26T11:35:38.003 回答
0

这是查询。我希望这可以帮助你

select b.artid,count(b.artid) from category a
inner join ArticleAssignedCategories b on a.itemid = b.artid
group by b.artid
于 2013-08-26T11:32:46.777 回答