Home  >  Article  >  Daily Programming  >  What does union mean in mysql

What does union mean in mysql

下次还敢
下次还敢Original
2024-04-27 03:54:15381browse

UNION is used in MySQL to merge query results. It combines matching rows in multiple result sets and removes duplicate rows. The query in the example will merge matching rows in the name column in the employees and customers tables. UNION ALL does not remove duplicate rows, and the UNION operator is non-commutative, which means the order of the result set depends on the order of the SELECT statements.

What does union mean in mysql

UNION in MySQL

UNION is used in MySQL to merge the results of two or more SELECT statements. Keywords. It combines matching rows from two or more result sets into a new result set.

Syntax

<code class="sql">SELECT ...
FROM ...
UNION
SELECT ...
FROM ...</code>

Behavior

The UNION operator has the following behavior:

  • Union Matching rows from different result sets, even if they come from different tables.
  • Delete duplicate matching lines.
  • If NULL values ​​exist in the result set, the row is retained, but NULL values ​​may interfere with the comparison.
  • Each SELECT statement must return the same number of columns, and the columns must be of compatible type and order.

Example

<code class="sql">SELECT name FROM employees UNION SELECT name FROM customers;</code>

This query will merge the name column from the employees and customers tables and remove duplicate names.

UNION ALL

UNION ALL is a variant of UNION that does not delete duplicate rows.

<code class="sql">SELECT name FROM employees UNION ALL SELECT name FROM customers;</code>

This query will merge the name column from the employees and customers tables and keep duplicate names.

Note

  • The UNION operator is non-commutative, which means that the order of the result set depends on the order of the SELECT statements.
  • When using UNION, you must ensure that the combined result set has a compatible structure. Otherwise, MySQL will throw an error.
  • UNION can be combined with other set operators such as INTERSECT and EXCEPT to create more complex result sets.

The above is the detailed content of What does union mean in mysql. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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