union and union all keywords

Features:

union: query the result set and perform a union operation to remove duplicate records, and only keep one

union all: query the result set and perform union operation without removing duplicate records

(1) Usage rules of union and union all:

  a. Generally used in DQL (select) syntax to remove duplicate records

  b. When using a joint query, the types of fields to be queried in each query statement need not be the same, but the number of fields to be queried must be consistent.

   If the number of fields to be queried in the former query statement is longer than the latter, or vice versa, an error will be reported.

  c. During the joint query, the field queried by the first query statement will be used as the field of the table after the joint query

  d. Syntax: (1) select field name 1, field name 2, ... from tablename1

       union

       select field name A, field name B, ... from tablename2;

 

      (2) select field name 1, field name 2, ... from tablename1

          union all

          select field name A, field name B, ... from tablename2;

Practice:

(1) The data of t_user and t_user1 are as follows:

     

 They have the same data in the name field of the two tables: KING and SMITH

 

(2) Perform union operation:

a. Query all the data in the name field of the t_user / t_user1 table, take the union and remove KING and SMITH, and only keep one

 

 b. Query all the data in the id and name fields of the t_user / t_user1 table, and take the union

 

 b. Query the id, name of t_user , query the id, name, sex of t_user1 , and perform a union operation. Because the number of fields is not the same length, an error will be reported.

 

c. Query the id and name of t_user , query the name and sex of t_user1 , and perform a union operation. Although the types of the fields are different, as long as the number and length of the fields are the same, they can be queried together.

 And the field queried by the first query statement will be used as the table field after the joint query.

 

(3) Perform union all operation:

Complete the union of the result set after the query, without duplication, we first change the data of the second and third items of t_user1 to KING to ensure that there is the same id and name data

 

Guess you like

Origin www.cnblogs.com/ibear/p/12675460.html