开发者

SQL query problem in table with self-referencing parent ID

First the relevent schema:

A is a table of list entries with ListID, Date, and ItemID

B is a table of the underlying items with ID and owner (which is currently text).

C is a table of the owners with ID (int), Name (varchar) and Parent (int). Parent is either the ID of another member or null if it is a top-level node. This table is开发者_StackOverflow社区 only 2 levels deep so every member is either a child or parent.

A.ItemID points to B.ID B.Owner points to C.Name C.Parent is either null or points to another C.ID

Now the problem...

I need to count the number of entries on a given list (ListID and Date) for each parent in C. I almost have it with one problem. Query is:

select C.owner, COUNT(B.ID) as Count from A  
join B on A.ItemID = B.ID  
join C on B.Owner= C.Owner  
join C2 on C.Parent = C2.ID   
Where date = '2011-01-10' and ListID = 1  
Group by C2.Owner  
order by C2.Owner  

But it is only counting entries that match up with child rows in C. Because the parent rows don't have their own ID in the parent field, they aren't being included in the aggregate counts even though there are items that are directly owned by parents in table C. I am fairly sure that I could solve the problem by putting those values in, but that seems like bad design as those rows would effectively be their own parents.

Is there a way to manage this query to account for this? I'm stumped.

Alternatively, is it 'okay' to have rows reference themselves as a parent for purposes of aggregating their own data with those of their children?

Thanks for any and all advice here. If this isn't clear, I can be more specific but I'm trying to keep unrelated information out of it.

-Dan


You need to use a left-join on C and C2.

C LEFT JOIN C2 ON C.Parent = C2.ID

This will cause all rows to be included from C, and, if there is a corresponding child in C2, that will be included as well.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜