Home > Database > SQL > body text

How to use union in sql

下次还敢
Release: 2024-05-07 04:54:14
Original
533 people have browsed it

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>
Copy after login

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>
Copy after login
Result set:

<code>| name |
| --- |
| John |
| Mary |
| David |
| Lisa |</code>
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!