Home > Database > Mysql Tutorial > How can I achieve a FULL JOIN effect in MySQL?

How can I achieve a FULL JOIN effect in MySQL?

DDD
Release: 2024-11-20 00:18:03
Original
642 people have browsed it

How can I achieve a FULL JOIN effect in MySQL?

MySQL FULL JOIN?

In MySQL, the FULL JOIN operation is not directly supported. However, it is possible to achieve a similar result using a combination of LEFT JOIN and RIGHT JOIN. Here's how you can do it:

SELECT
    t1.column1,
    t2.column2
FROM
    table1 AS t1
LEFT JOIN
    table2 AS t2
ON
    t1.id = t2.id
UNION ALL
SELECT
    t1.column1,
    NULL
FROM
    table1 AS t1
RIGHT JOIN
    table2 AS t2
ON
    t1.id = t2.id
WHERE
    t2.id IS NULL
Copy after login

In this query, the LEFT JOIN retrieves all the rows from table1 and matches them with corresponding rows from table2 based on the id column. The RIGHT JOIN retrieves all the rows from table2 and matches them with corresponding rows from table1. The UNION ALL operator combines the results of both joins.

Let's say we have two tables, "Persons" and "Orders", with the following data:

Persons
P_Id LastName FirstName
1 Hansen Ola
2 Pettersen Kari
3 Svenson Tove
Orders
OrderNo P_Id
22456 1
24562 1
77895 2
44678 2
34764 3

To get the following result using the above query:

LastName FirstName OrderNo
Hansen Ola 22456
Hansen Ola 24562
Pettersen Kari 77895
Pettersen Kari 44678
Svenson Tove 34764

Simply replace table1 with "Persons" and table2 with "Orders" in the query and execute it.

The above is the detailed content of How can I achieve a FULL JOIN effect 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template