Home >Database >SQL >What does union in sql mean?

What does union in sql mean?

下次还敢
下次还敢Original
2024-05-01 23:30:44499browse

The UNION operator in SQL is used to merge data in tables. Its characteristics are: merging tables, requiring column matching, and retaining duplicate rows. Uses include: merging complementary data, finding duplicate data, creating summary reports, and deduplicating data. Example: SELECT customer_id, first_name, last_name FROM customers UNION SELECT customer_id, first_name, last_name FROM orders; will merge customer data from the customers and orders tables, including duplicate rows.

What does union in sql mean?

UNION in SQL

UNION is an operator in SQL that is used to Merge data from two or more tables. It appends the rows from the input table together to create a new results table.

Syntax

<code class="sql">SELECT 列名1, 列名2, ...
FROM 表1
UNION
SELECT 列名1, 列名2, ...
FROM 表2;</code>

Features

  • Merge tables: UNION merges two or More table rows.
  • Column matching: The tables to be merged must have the same number of columns and data types.
  • Result order: The rows in the result table are arranged in the order of the input table.
  • Duplicate rows: Unlike INTERSECT and EXCEPT, UNION will retain duplicate rows.

Usage

UNION is mainly used in the following situations:

  • Merge complementary data from different tables:For example, merge two customer tables with different fields to create a more comprehensive view.
  • Find duplicate data in different tables: Use UNION ALL (without DISTINCT) to find duplicate rows across tables.
  • Create summary report: Combine summary data from multiple tables into one table.
  • Eliminate duplicate data: Before using UNION, use the DISTINCT keyword to eliminate duplicate rows.

Example

The following example merges customer data from two tables named customers and orders For a result table:

<code class="sql">SELECT customer_id, first_name, last_name
FROM customers
UNION
SELECT customer_id, first_name, last_name
FROM orders;</code>

The result table will contain customer information from both tables, including duplicate rows.

The above is the detailed content of What does union in sql mean?. 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