Efficient way to simulate full outer join in MySQL?

落爺英雄遲暮 提交于 2019-11-28 00:58:29

问题


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 duplicates or show spurious duplicates.

What would be correct and efficient way?

This question seems relevant but couldn't get the answer of it.


回答1:


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.



来源:https://stackoverflow.com/questions/3447215/efficient-way-to-simulate-full-outer-join-in-mysql

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!