In MySQL, the UNION operator merges result sets from multiple tables or subqueries, returning only unique result rows. It is primarily used to merge disjoint result sets and allows retaining duplicate rows via UNION ALL.
UNION usage in MySQL
UNION operator is used in MySQL to merge from Result set of multiple tables or subqueries. It only returns unique result rows without repeating the same rows.
Syntax:
<code>SELECT 列名1, 列名2, ... FROM 表名1 UNION SELECT 列名1, 列名2, ... FROM 表名2 ... [UNION ALL]</code>
Parameters:
Usage:
UNION is mainly used to merge disjoint result sets from different tables or subqueries. It only keeps unique result rows.
For example, to merge the result sets of tables customers
and orders
and display each customer's information and order information, you can use the following query:
<code>SELECT * FROM customers UNION SELECT * FROM orders;</code>
If you want to keep duplicate rows, you can use UNION ALL
:
<code>SELECT * FROM customers UNION ALL SELECT * FROM orders;</code>
Note:
CAST()
or CONVERT()
) to ensure they are compatible. The ORDER BY
clause is used. The above is the detailed content of How to use union in mysql. For more information, please follow other related articles on the PHP Chinese website!