Home  >  Article  >  Database  >  How to use union in sql

How to use union in sql

下次还敢
下次还敢Original
2024-05-07 04:54:14529browse

The UNION operator combines the results of multiple SELECT statements into a result set that does not contain duplicate rows. Its characteristics include: the column order and data type of the merged result set must be the same. Aggregate functions are not supported. UNION ALL can be used to combine result sets that contain duplicate rows to find duplicate data.

How to use union in sql

Usage of UNION in SQL

The UNION operator is used in SQL to combine two or more SELECT The results of the statements are combined into a result set.

Usage:

SELECT statement UNION SELECT statement UNION...

Features:

  • The merged result set contains only unique rows.
  • The order and data type of the columns in the merged result set must be the same.
  • UNION does not support aggregate functions (such as SUM, COUNT).
  • If you want to merge result sets that contain duplicate rows, you can use UNION ALL.

Example:

Suppose we have two tables:

<code>表 Student:
| id | name |
| --- | ---- |
| 1    | John |
| 2    | Mary |

表 Teacher:
| id | name |
| --- | ---- |
| 3    | David |
| 4    | Lisa |</code>

We can use the UNION operator to merge the # of these two tables ##name Column:

<code class="sql">SELECT name FROM Student
UNION
SELECT name FROM Teacher;</code>
Result set:

<code>| name |
| --- |
| John |
| Mary |
| David |
| Lisa |</code>

Note:

    Before using UNION, make sure the result set The column order and data type are consistent.
  • If the result set contains duplicate rows, UNION will automatically delete them.
  • UNION ALL allows you to merge result sets that contain duplicate rows, so it can be used to find duplicate data.

The above is the detailed content of How to use union in sql. 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
Previous article:How to use drop in sqlNext article:How to use drop in sql