MySQL: difference between union and union all

1. Difference

1. The display results are different

union will automatically compress duplicate results in multiple result sets, while union all will display all the results.

2. The processing of repeated results is different, and the performance is also different

Union all is a direct connection, and all values ​​are obtained, and records may be duplicated; union is a unique value, and records are not duplicated. Therefore, union will filter out duplicate records after table linking, and union all will not remove duplicate records.

3. The processing of sorting is different

union will sort in the order of the fields; union all simply combines the two results and returns. In terms of efficiency, union all is much faster than union, so if you can confirm that the two merged result sets do not contain duplicate data and do not need to be sorted, then use union all.

Precautions:

1. Both union and union all can combine multiple result sets, not just two, so multiple result sets can be strung together. 

2. When using union and union all, you must ensure that the results of each select set have the same number of columns, and the type of each column is the same. But the column names do not necessarily need to be the same, oracle will use the column names of the first result as the column names of the result set.

2. How to use

1. union: used to combine multiple select query results.

2. union all: used to combine multiple select query results.

3. The requirements of union and union all for the select statement:

   (1) In each select query statement, the number of columns for each select query must be the same, and the number of columns for one select query cannot be 4 columns, while the number of columns for another select query is 7 columns.

   (2) In each select query statement, the data type of each column must be the same or similar. The first column of one select cannot be of int type, while the first column of another select is of nvarchar type.
 

Guess you like

Origin blog.csdn.net/qq_39367410/article/details/127649926