📅  最后修改于: 2023-12-03 15:03:07.633000             🧑  作者: Mango
MySQL UNION is a SQL operator that combines the result sets of two or more SELECT statements. It allows programmers to perform complex queries that involve combining data from different tables or queries in a single result set.
The syntax of the UNION operator in MySQL is as follows:
SELECT column1, column2, ... FROM table1
UNION [ALL]
SELECT column1, column2, ... FROM table2
[UNION [ALL] SELECT column1, column2, ... FROM table3];
The SELECT statements involved in the UNION operator must have the same number of columns. The column names need not be identical, but they must have the same data types.
The UNION operator by default removes duplicate rows from the result set. If the programmer needs to include all rows, including duplicates, they can use the keyword ALL after the UNION operator.
Assuming that we have two tables named "employees" and "customers". Both tables have columns "name" and "id".
To combine the records from both tables and retrieve a single result set containing all the data, we can use the following SQL query:
SELECT name, id FROM employees
UNION
SELECT name, id FROM customers;
This query will return all the names and ids of the employees and customers in a single result set without any duplicates.
MySQL UNION is a powerful SQL operator that allows programmers to combine the result sets of two or more SELECT statements. It is useful when working with complex queries that involve fetching data from different tables or queries. By understanding how to use the UNION operator, programmers can make their database queries more efficient and effective.