The UNION operator is used in SQL to merge rows with the same structure, producing a table containing all unique rows. It works by merging result sets, removing duplicate rows and returning remaining rows. Unlike UNION ALL, UNION returns only unique rows. When using UNION, note that both tables must have the same number of columns and data types.
UNION meaning in SQL
UNION is a SQL operator used to combine values from two or Rows from multiple tables with the same structure (number of columns and data types). It creates a new table containing all unique rows that either exist in the first table or the second table.
How UNION works
The UNION operator works through the following steps:
The difference between UNION and UNION ALL
The UNION ALL operator is similar to UNION, but it does not delete duplicate rows. UNION ALL returns all merged rows, including duplicate rows.
UNION syntax
The basic form of UNION syntax is as follows:
<code class="sql">SELECT 列名1, 列名2, ... FROM 表名1 UNION SELECT 列名1, 列名2, ... FROM 表名2;</code>
For example, the following query uses the UNION operator to merge from two tables Data for students
and teachers
:
<code class="sql">SELECT id, name FROM 学生 UNION SELECT id, name FROM 教师;</code>
This will create a new table containing the id and name of all students and the id and name of all teachers. Note that if the Student
and Teacher
tables have the same id value, they will only be listed once.
Notes on using UNION
When using UNION, you need to pay attention to the following:
The above is the detailed content of what does union mean in sql. For more information, please follow other related articles on the PHP Chinese website!