Select Parent Record With All Children in SQL

后端 未结 3 717
眼角桃花
眼角桃花 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:21

    ( I guess where you said "Child Eve references Eve" you meant "Child Eve references Bob", right?)

    I think I've got it... looks ugly... the secret is the double negation... that is, everyone for which it's true,, is the same as not anyone for which is false... (ok, I have troubles with my english, but I guess you understand what I mean)

    select * from parent
    
    parent_id                               name
    --------------------------------------- --------------------------------------------------
    1                                       alice
    2                                       bob
    
    select * from child
    
    child_id                                name
    --------------------------------------- --------------------------------------------------
    1                                       charlie
    2                                       david
    3                                       eve
    
    select * from parent_child
    
    parent_id                               child_id
    --------------------------------------- ---------------------------------------
    1                                       1
    2                                       1
    1                                       2
    2                                       3
    
    select * from parent p 
    where not exists(
        select * from child c 
        where
            c.child_id in ( 1, 2, 3 ) and 
            not exists(
                select * from parent_child pc where
                    pc.child_id = c.child_id and
                    pc.parent_id = p.parent_id
            )
    )
    
    --when child list = ( 1 )
    parent_id                               name
    --------------------------------------- --------------------------------------------------
    1                                       alice
    2                                       bob
    
    --when child list = ( 1, 2 )
    parent_id                               name
    --------------------------------------- --------------------------------------------------
    1                                       alice
    
    --when child list = ( 1, 2, 3 )
    parent_id                               name
    --------------------------------------- --------------------------------------------------
    
    

    well, I hope it helps...

提交回复
热议问题