2013-08-26 5 views
0

SQL Server 쿼리에 지정된 ID의 모든 자식을 얻는 방법 :내가 SQL Server 데이터베이스에 두 개의 테이블이

category( 
    itemid, 
    parentid 
) 

ArticleAssignedCategories(
    categid, 
    artid 
) 

categid 내가 artids의 수를 얻으려면 itemid

의 외래 키 그 자식은 주어진 itemid (어린이는 parentid이 주어진 범주를 의미합니다)

예를 들어, category는 3, 4, 5의 자녀 (3,1), (4,1) (5,3)입니다했다

모든 대하여 itemid = 1 경우 테이블에서 1

사람은 쓰기 위해 도와 줄 수 좋은 쿼리?

+1

사용하여 수행 할 수 있습니다 도움이 될 수 있기를 바랍니다. http://stackoverflow.com/questions/12858567/how-to-get-all-children-and-itself-from-hierarchical-data-with-cte-in-sql-server –

답변

1

재귀 쿼리 당신은 재귀 CTE를 사용할 수 있습니다 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 
0

다음은 쿼리입니다. 나는 이것이 당신

select b.artid,count(b.artid) from category a 
inner join ArticleAssignedCategories b on a.itemid = b.artid 
group by b.artid