Home > Database > SQL > body text

The role of union in sql

下次还敢
Release: 2024-05-02 00:00:26
Original
789 people have browsed it

The UNION operator combines rows from multiple tables with the same column structure into a single result set, eliminating duplicate rows and automatically converting data types. 1. Merge rows from different tables; 2. Eliminate duplicate rows; 3. Convert data types to match column structure.

The role of union in sql

The role of UNION in SQL

The UNION operator is used to merge data from two or more tables with Rows with the same column structure form a new result set.

Usage:

The syntax of UNION is as follows:

<code>SELECT 列名1, 列名2, ...
FROM 表名1
UNION
SELECT 列名1, 列名2, ...
FROM 表名2</code>
Copy after login

Function:

  • Merge rows: Merge rows from multiple tables together to form a new result set.
  • Eliminate duplicate rows: By default, UNION will eliminate duplicate rows.
  • Different tables: Rows from different tables can be merged as long as they have the same column structure.
  • Data type conversion: UNION will automatically convert columns of different data types into compatible data types.

Notes:

  • Column order and data type:The columns of the merged table must be in the same order and Data type arrangement.
  • NULL values: UNION treats NULL values ​​as matching values ​​even if they appear in different columns in different rows.
  • ALL and DISTINCT: UNION can use ALL or DISTINCT keywords, ALL contains all rows and DISTINCT returns only unique rows.

Example:

Merge rows from two tables containing country information:

<code>SELECT Country, Population
FROM Countries
UNION
SELECT Country, Population
FROM World_Nations;</code>
Copy after login

Result:

The merged table will contain data for all countries with no duplicate rows.

The above is the detailed content of The role of 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!