Home > Database > Mysql Tutorial > How Can I Simulate a FULL OUTER JOIN in MySQL?

How Can I Simulate a FULL OUTER JOIN in MySQL?

Susan Sarandon
Release: 2025-01-25 13:42:11
Original
590 people have browsed it

How Can I Simulate a FULL OUTER JOIN in MySQL?

Simulate FULL OUTER JOIN in MySQL

MySQL itself does not support FULL OUTER JOIN. However, you can simulate it using a combination of LEFT JOIN, RIGHT JOIN, and set operators.

LIMITED FULL OUTER JOIN

For cases where FULL OUTER JOIN does not produce duplicate rows, you can use:

<code class="language-sql">SELECT * 
FROM t1
LEFT JOIN t2 
ON t1.id = t2.id
UNION
SELECT * 
FROM t1
RIGHT JOIN t2 
ON t1.id = t2.id</code>
Copy after login

The UNION operator eliminates duplicate rows introduced by this query pattern.

General FULL OUTER JOIN

For the common case where duplicate rows may occur, use:

<code class="language-sql">SELECT * 
FROM t1
LEFT JOIN t2 
ON t1.id = t2.id
UNION ALL
SELECT * 
FROM t1
RIGHT JOIN t2 
ON t1.id = t2.id
WHERE t1.id IS NULL</code>
Copy after login

The UNION ALL operator combines the results of two JOINs, and the additional WHERE clause ensures that only rows with t1.id NULL (not matched in the LEFT JOIN) are added to the final result, thus eliminating duplicates.

The above is the detailed content of How Can I Simulate a FULL OUTER JOIN in MySQL?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template