sql - How to query items that have full match of its children in Child table -
i have 2 tables: parentchild , child.
parentchild table has 2 columns pid , cid, 1 pid can map multiple cids. child table contains distinct cids. thing cids in child table doesn't cover cids in parentchild table.
now want find pids each pid has cids in child table. examples: p1 has 3 cids, if in child table, p1 selected; p2 has 2 cids, if not in child table, p2 not selected.
how write query in clear , performant way?
one method uses aggregation:
select pc.pid parentchild pc left join child c on pc.cid = c.cid group pc.pid having count(*) = count(c.cid);
the last condition checks children match.
Comments
Post a Comment