sql - MySQL how to find parent with exact set of children? -
mysql 5.5
parent table: id | facts
child table: parent_id | foreign_key | facts
now, want find parents have exact set of children, no more, no less. like:
select t1.`id` `parent_table` t1 left join `child_table` t2 on t1.id=t2.parent_id t2.`fk` = 1 , t2.`fk` = 3 , t2.`fk` = 5 , t2.`fk` = 7 , t2.`fk` = 9
but parent record set of children: 1,2,3,5,7,9. , want parents have the exact set of children: 1,3,5,7,9.
is there way?
edit: child.parent_id , child.fk both not unique. child.fk foreign key linking table. ("many-to-many relationship") quite possible parent have children 1,2,3,5,7,9. whole reason doing query try avoid creating new parent 1,3,5,7,9 if such parent exists.
assuming child.id
unique every child.parent_id
.
select a.id, a.facts parent inner join child b on a.id = b.parent_id b.id in (1,3,5,7,9) , -- <<== list childid here exists -- <<== part checks if parent_id ( -- present on exists clause select parent_id -- filters parents child c -- 5 children b.parent_id = c.parent_id group parent_id having count(*) = 5 -- <<== total number of children ) group a.id, a.facts having count(*) = 5 -- <<== total number of children
Comments
Post a Comment