Efficient way to simulate full outer join in MySQL?

前端 未结 1 756
故里飘歌
故里飘歌 2020-12-10 16:50

According to Google search: since MySQL does not support full outer join, it could be simulated via union and/or union all. But both of these either remove genuine duplicate

1条回答
  •  独厮守ぢ
    2020-12-10 17:09

    You can use a LEFT JOIN and a RIGHT JOIN:

    SELECT * FROM tableA LEFT JOIN tableB ON tableA.b_id = tableB.id
    UNION ALL
    SELECT * FROM tableA RIGHT JOIN tableB ON tableA.b_id = tableB.id
    WHERE tableA.b_id IS NULL
    

    There is also some information on Wikipedia about this topic: Full outer join.

    The Wikipedia article suggests using a UNION in MySQL. This is slightly slower than UNION ALL, but more importantly it won't always give the correct result - it will remove duplicated rows from the output. So prefer to use UNION ALL instead of UNION here.

    0 讨论(0)
提交回复
热议问题