📜  MySql FULL OUTER JOIN - SQL (1)

📅  最后修改于: 2023-12-03 15:33:01.573000             🧑  作者: Mango

MySql FULL OUTER JOIN - SQL

MySQL FULL OUTER JOIN is used to combine two or more tables together. This type of JOIN operation returns all records from both tables, matched records from either table or unmatched records from either table.

Syntax
SELECT column, column, ...
FROM table1
FULL OUTER JOIN table2
ON table1.column = table2.column;
Example

Suppose we have two tables named "customers" and "orders".

Table customers:

+----+----------+-----+----------+
| id | name     | age | address  |
+----+----------+-----+----------+
|  1 | John Doe |  30 | USA      |
|  2 | Jane Doe |  25 | Canada   |
|  3 | Tom Jerry|  40 | UK       |
+----+----------+-----+----------+

Table orders:

+----+------------+----------+
| id | order_date | customer |
+----+------------+----------+
|  1 | 2022-01-01 |    1     |
|  2 | 2022-01-02 |    4     |
|  3 | 2022-01-03 |    2     |
+----+------------+----------+

Now if we want to combine both tables using FULL OUTER JOIN on the "id" column, we can use the following SQL statement:

SELECT *
FROM customers
FULL OUTER JOIN orders
ON customers.id = orders.customer;

This will give us the result:

+------+----------+------+-----------+------+------------+----------+
| id   | name     | age  | address   | id   | order_date | customer |
+------+----------+------+-----------+------+------------+----------+
| 1    | John Doe | 30   | USA       | 1    | 2022-01-01 | 1        |
| 2    | Jane Doe | 25   | Canada    | 3    | 2022-01-03 | 2        |
| 3    | Tom Jerry| 40   | UK        | NULL | NULL       | NULL     |
| NULL | NULL     | NULL | NULL      | 2    | 2022-01-02 | 4        |
+------+----------+------+-----------+------+------------+----------+

As we can see, the FULL OUTER JOIN has combined both tables together and returned all records from both tables, matched records from either table or unmatched records from either table.

If both tables have matching records, those records will be included in the result set. If a record in one table does not have a corresponding record in the other table, NULL values will be returned for the missing column(s).

Conclusion

MySQL FULL OUTER JOIN is a powerful tool for combining data from two or more tables. It can be used to retrieve all records from both tables, regardless of whether they match or not. By using this type of JOIN, you can bring together data from multiple sources to create a comprehensive view of your data.