문제

So I have a SQL query like this:

SELECT p.*
FROM parent p JOIN join_table j ON p.id=j.parent_id
WHERE j.child_id=1 OR j.child_id=2
GROUP BY j.parent_id
HAVING COUNT(j.child_id)=2;

Which I got from this excellent answer here. Now I would like to modify the query to return the count of all the parent elements there. unfortunately due to the GROUP BY statement I am unable to do this (as it will give the count of each grouped statement).

My attempt was the obvious and naive approach:

SELECT COUNT(DISTINCT(p.id))
FROM parent p JOIN join_table j ON p.id=j.parent_id
WHERE j.child_id=1 OR j.child_id=2
GROUP BY j.parent_id
HAVING COUNT(j.child_id)=2;

Thanks for helping.

도움이 되었습니까?

해결책

Try this:

SELECT COUNT(*) FROM
   (SELECT p.*
   FROM parent p JOIN join_table j ON p.id=j.parent_id
   WHERE j.child_id=1 OR j.child_id=2
   GROUP BY j.parent_id
   HAVING COUNT(j.child_id)=2) AS res;

다른 팁

SELECT SUM(CN) FROM (    
  SELECT p.*, count(*) cn
  FROM parent p JOIN join_table j ON p.id=j.parent_id
  WHERE j.child_id=1 OR j.child_id=2
  GROUP BY j.parent_id
  HAVING COUNT(j.child_id)=2
);

This should give you the total count

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top