Introduction
The UNION operator is used to combine the result set of two or more SELECT statements. For example, I have two tables, and table 1 records data about the company's male employees, including age, name, and position. Table 2 records data about female employees, including names, home addresses, cell phone numbers, and so on. At this point, we want to query the collection of the names of two tables according to certain conditions. You will use the UNION keyword.
UNION can query multiple fields, but the SELECT statement must have the same number of columns. The column must also have a similar data type. Also, the order of the columns in each SELECT statement must be the same.
Grammar
1 SELECT from table_name1 2 UNION 3 SELECT from Table_name2
The UNION operator will de-weight the result set. If you allow duplicate values, you can use the UNION all to remove the heavy function, no other difference.
Example
Here is an example of the introduction of the introduction for the requirements, the establishment of two tables, and the corresponding operation.
First, create a user1,user2 two table with the following statement:
1 --build a Table statement2 CREATE TABLEUser1 (3IdINT,4AgeINT,5NAMEVARCHAR(5),6PositionVARCHAR(8)7 );8 CREATE TABLEUser2 (9IdINT,TenNameVARCHAR(5), OneAddressVARCHAR( -), APhone_numberVARCHAR( -) -)
CREATE TABLE
Next, insert the corresponding data, SQL as follows:
1 --Data INSERT statement2 INSERT intoUser13 VALUES4 (5 1,6 -,7 'Zhang San',8 'Technical Director'9 );Ten One INSERT intoUser1 A VALUES - ( - 2, the -, - 'John Doe', - 'Product Supervisor' - ); + - INSERT intoUser1 + VALUES A ( at 3, - -, - 'Harry', - 'Operations Supervisor' - ); - in INSERT intoUser1 - VALUES to ( + 4, - -, the 'Zhao Liu', * 'Logistics Supervisor' $)INSERT intoUser2 (Panax Notoginseng ID, - NAME, the address, + Phone_number A ) the VALUES + ( - 1, $ 'Jean Jean', $ 'Beijing', - '155332211' - ); the - INSERT intoUser2 (Wuyi ID, the NAME, - address, Wu Phone_number - ) About VALUES $ ( - 2, - 'Lian Lian', - 'Shanghai', A '155332211' + ); the - INSERT intoUser2 ( $ ID, the NAME, the address, the Phone_number the ) - VALUES in ( the 3, the 'Love Love', About 'Shenzhen', the '155332211' the);
INSERT
Finally, run the Union statement to query
1 -- UNION Statement 2 SELECT from User1 3 UNION 4 SELECT from User2
UNION
After the code executes, the results are as follows:
The column name for the first SELECT statement in the result set here is the Union statement (User1 is name, User2 is name).
Explain, the ID is null
The execution ID of the last merge result set operation is null at the time the execution plan for the Union is executed. Furthermore, the first execution of the Select_type is a simple query, the second and subsequent queries are union, and the final merge Select_type is union RESULT.
The execution plan code is as follows:
SELECT from User1 UNION SELECT from User2
EXPLAIN UNION
The results are as follows: