In SQL / MySQL, what is the difference between “ON” and “WHERE” in a join statement?

前端 未结 6 1936
臣服心动
臣服心动 2020-11-27 13:23

The following statements give the same result (one is using on, and the other using where):

mysql> select * from gifts INNER JOI         


        
6条回答
  •  盖世英雄少女心
    2020-11-27 13:58

    • ON is applied to the set used for creating the permutations of each record as a part of the JOIN operation
    • WHERE specifies the filter applied after the JOIN operation

    In effect, ON replaces each field that does not satisfy its condition with a NULL. Given the example by @Quassnoi

    gifts
    
    1   Teddy bear
    2   Flowers
    
    sentgifts
    
    1   Alice
    1   Bob
    
    ---
    SELECT  *
    FROM    gifts g
    LEFT JOIN
            sentgifts sg
    ON      g.giftID = sg.giftID
    
    ---
    

    The LEFT JOIN permutations would have been calculated for the following collections if there was no ON condition:

    { 'Teddy bear': {'ALICE', 'Bob'}, 'Flowers': {'ALICE', 'Bob'} }

    with the g.giftID = sg.giftID ON condition, this is the collections that will be used for creating the permutations:

    { 'Teddy bear': {'ALICE', 'Bob'}, 'Flowers': {NULL, NULL} }

    which in effect is:

    { 'Teddy bear': {'ALICE', 'Bob'}, 'Flowers': {NULL} }

    and so results in the LEFT JOIN of:

    Teddy bear Alice
    Teddy bear Bob
    Flowers    NULL
    

    and for a FULL OUTER JOIN you would have:

    { 'Teddy bear': {'ALICE', 'Bob'}, 'Flowers': {NULL} } for LEFT JOIN and { 'ALICE': {'Teddy bear', NULL}, 'Flowers': {'Teddy bear', NULL} } for RIGHT JOIN:

    Teddy bear Alice
    Teddy bear Bob
    Flowers    NULL
    

    If you also had a condition such as ON g.giftID = 1 it would be

    { NULL: {'ALICE', 'Bob'}, 'Flowers': {NULL} }

    which for LEFT JOIN would result in

    Flowers NULL

    and for a FULL OUTER JOIN would result in { NULL: {'ALICE', 'Bob'}, 'Flowers': {NULL} } for LEFT JOIN and { 'ALICE': {NULL, NULL}, 'Flowers': {NULL, NULL} } for RIGHT JOIN

    NULL    Alice
    NULL    Bob
    Flowers NULL
    

    Note MySQL does not have a FULL OUTER JOIN and you need to apply UNION to LEFT JOIN and RIGHT JOIN

提交回复
热议问题