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.
I wonder if I understood your question well, could you try this?