Reputation: 7788
I'm working with a recursive table and I'm trying to build a query to get my child node counts however my query fails to return the correct count when I restrict it by the basic_user_id
.
The idea behind the design is to enable different users to have their own hierarchy of companies, however I can't have them conflicting with each other which is what appears to be happening.
My query
select * , count(c2.company_id )
from company_user c1 left join company_user c2 on c2.parent_id = c1.company_id
where c1.company_id in (1337)
and c1.basic_user_id = 23
group by c1.company_id;
basic_user_id = 23
should return a count of 1 which it does correctly
Now when I change basic_user_id
to 541, I'm expecting it to return a count of 0 however it still seems to return a count of 1.
How do I get basic_user_id = 541
to return a count of 0 and basic_user_id = 23
to return a count of 1?
Upvotes: 1
Views: 348
Reputation: 10236
Could you try this? You can test here. http://www.sqlfiddle.com/#!2/73f61/2
I have added AND child_tab.basic_user_id = parent_tab.basic_user_id
ON clause. Because You are doing LEFT JOIN
SELECT parent_tab.company_id, COUNT(child_tab.company_id)
FROM company_user parent_tab LEFT JOIN company_user child_tab
ON child_tab.parent_id = parent_tab.company_id
AND child_tab.basic_user_id = parent_tab.basic_user_id
WHERE parent_tab.company_id IN (1337)
AND parent_tab.basic_user_id = 23
GROUP BY parent_tab.company_id;
Upvotes: 1
Reputation: 1011
change
count(c2.company_id )
to
sum(case when c2.company_id is null then 0 else 1 end)
(please check syntax of case statement for your DB)
Upvotes: 0
Reputation: 7788
Resolved, I just needed to add a second join.
select * , count(c2.company_id )
from deepblue.company_user c1 left join deepblue.company_user c2 on c2.parent_id = c1.company_id
and c1.basic_user_id = c2.basic_user_id
where c1.company_id in (1337)
and c1.basic_user_id= 541
group by c1.company_id;
Upvotes: 1