MySQL: Multiple subqueries and where in join clauses

436 views Asked by At

So I have three tables;

grandparent, parent, and child.

parent and child each have a parent field.

I want to find all the grandchildren of the grandparent where all the grandchildren are married and the grandparent is over 80. Lets assume each grandparent can only have 4 grandchildren.

So I start with a select on the grandparent table:

select id from grandparent where age > 80

This will give me a set of grandparents whose age is greater than 80.

Then I find the parents in the parent table grouped by their grandparent;

select group_concat(id) as grandparent from parent where parent in (
    select id from grandparent where age > 80
) group by parent

This gives me a set of parents for each row of grandparents, something like

grandparent: (1,2,3,4)
grandparent: (5,6,7,8)
grandparent: (9,10,11,12)

Now I want to find all the children of these parents where they are all married, so far I have something like;

select
    group_concat(parent) as parent
    group_concat(id) as children
from child
where
    parent in (
        select group_concat(id) as grandparent from parent where parent in (
            select id from grandparent where age > 80
        ) group by parent
    )
    and relationship_status = "MARRIED"
having count(id) = 4;

But obviously it doesn't work because I need the in clause to search the sets of each row returned from the previous query.

How would I run the above query for each row set?

Note: These aren't the real names of my tables or fields, just removing domain knowledge so it's hopefully easier to help.

1

There are 1 answers

0
Jason Heo On BEST ANSWER

I wonder if I understood your question well, could you try this?

SELECT p.parent_id, GROUP_CONCAT(p.parent), GROUP_CONCAT(c.id)
FROM grantparent gp INNER JOIN parent p gp.id = p.parent
  INNER JOIN child c ON c.parent = p.id
WHERE gp.age > 80 AND c.relationship_status = 'MARRIED'
GROUP BY p.parent_id
HAVING COUNT(c.id) = 4;