Union is used to merge two or more select statements and output similar data in multiple tables in one column.
Note:: (1) by default, the Union statement returns only different values. If you do not want to duplicate values, you can use Union all
(2)The number of columns queried by the SELECT statement before and after union must be the same as that in the order before and after union, and the columns must have similar data types. In a simple statement, the columns and column names of two tables can be different, but the two tables have data columns of the same type. The columns in the query statement must be both of them, the order of the columns written by the statement must be the same.
(3) The name of the output result column is the same as that given by the first select statement.
11.1 Union syntax
Select column name from table name 1
Union
Select column name from table name 2
Note: The first column name is the column name in table 1, and the second column name is the column name corresponding to the column in table 2.
11.1 Union instance
The sample data is as follows: table_1 Table_2
Requirements: Obtain the name, address, and School of the middle school student in Table 1, table 2.
The statement is as follows:
Select name, address, school from table_2
Union
Select name, ardess, schoolFrom table_1
Execution result:
In table 1, Table 2 has flowers and plants in Beijing, removing duplicates and retaining only one result. The column name is the column name of table 2, because the SELECT statement of table 2 is placed in front.
The Union all statement is as follows:
Select name, address, school from table_2
Union all
Select name, ardess, schoolFrom table_1
Execution result
We can see that the only difference between Union all and union is that they are not heavy.
Note: When the Union statement is used, order by is not allowed, but the order by statement can be placed after the last SELECT statement to sort the final result.