grammar:
UNION
operator used to combine SELECT
the results of two statements
SELECT statement
UNION [DISTINCT | ALL]
SELECT statement
UNION
SELECT
The number of columns and the order of columns must be the same in the statements in
UNION is a binocular operator that requires two SELECT statements as operands. UNION can be followed by DISTINCT or ALL
If DISTINCT or ALL is not written, the default is UNION DISTINCT
UNION DISTINCT
Or UNION
will filter out duplicate records in the result set
UNION ALL returns all results
Create test data
CREATE TABLE a (v INT);
CREATE TABLE b (v INT);
CREATE TABLE c (v INT);
INSERT INTO a VALUES (1), (2), (NULL), (NULL);
INSERT INTO b VALUES (2), (2), (NULL);
INSERT INTO c VALUES (3), (2);
a table:
table b:
c-table:
example:
SELECT * FROM a UNION SELECT * FROM b;
We can see that repeated NULLs have been deduplicated
You can also use multiple UNIONs in conjunction
SELECT * FROM a UNION SELECT * FROM b UNION SELECT * FROM c;
In principle, we only require that the column names on both sides of the UNION be the same, not the same, but the official document requires that the column names must be the same, otherwise it may cause schema errors
However, if in general, when we UNION two different column names, the column name of the merged result is the same as the first operand of UNION