Question

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.

Was it helpful?

Solution

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;

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top