Select Parent Record With All Children in SQL

后端 未结 3 709
眼角桃花
眼角桃花 2021-02-15 11:42

Let\'s say I have two tables, \"Parent\" and \"Child\". Parent-to-Child is a many:many relationship, implemented through a standard cross-referencing table.

I want to fi

3条回答
  •  广开言路
    2021-02-15 12:08

    Relying on a numerical trick (where the number of parent-child links = the number of children, that parent is linked to all children):

    SELECT Parent.ParentID, COUNT(*)
    FROM Parent
    INNER JOIN ChildParent
        ON ChildParent.ParentID = Parent.ParentID
    INNER JOIN Child
        ON ChildParent.ChildID = Child.ChildID
    WHERE 
    GROUP BY Parent.ParentID
    HAVING COUNT(*) = (
        SELECT COUNT(Child.ChildID)
        FROM Child WHERE 
    )
    

提交回复
热议问题