SQL UNION operator

Please indicate the source of the original reprint: http://agilestyle.iteye.com/blog/2340901

 

SQL UNION operator

The UNION operator is used to combine the result sets of two or more SELECT statements.

Note: Each SELECT statement inside a UNION must have the same number of columns. Columns must also have similar data types. Also, the order of the columns in each SELECT statement must be the same.

 

SQL UNION syntax

SELECT column_name(s) FROM table1
UNION
SELECT column_name(s) FROM table2;

Note: By default, the UNION operator selects distinct values, i.e. no repetitions. 

 

SQL UNION ALL syntax

SELECT column_name(s) FROM table1
UNION ALL
SELECT column_name(s) FROM table2;

Note: The column names in the UNION result set are always equal to the column names in the first SELECT statement in UNION, and UNION ALL allows duplicates.

 

Example

desc websites;

 

desc apps;

 

select * from websites;

 

select * from apps;

 

SQL UNION instance

SELECT country FROM websites
UNION
SELECT country FROM apps
ORDER BY country;

Note: UNION cannot be used to list all countries in both tables. If some websites and apps are from the same country, each country will only be listed once. UNION just picks distinct values.

 

SQL UNION ALL instance

SELECT country FROM websites
UNION ALL
SELECT country FROM apps
ORDER BY country;

Note: Use UNION ALL to select duplicate values


 

SQL UNION ALL with WHERE

SELECT country, name FROM websites
WHERE country='CN'
UNION ALL
SELECT country, app_name FROM apps
WHERE country='CN'
ORDER BY country;


 
 
 


 
 

 

 

 

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326486937&siteId=291194637