MYSQL UNION
Combining SELECT statements with UNION
You can combine the results of two identically structured queries with the UNION keyword.
For example, if you wanted a list of all contact info from two separate tables, authors and editors, for instance, you could use the UNION keyword like so:
select name, email, phone_number
from authors
union
select name, email, phone_number
from editors
Using union by itself will strip out duplicates. If you needed to keep duplicates in your query, you could use the ALL keyword like so: UNION ALL.
Combining data with dierent columns
SELECT name, caption as title, year, pages FROM books
UNION
SELECT name, title, year, 0 as pages FROM movies
When combining 2 record sets with different columns then emulate the missing ones with default values.
ORDER BY
If you need to sort the results of a UNION, use this pattern:
( SELECT ... )
UNION
( SELECT ... )
ORDER BY
Without the parentheses, the final ORDER BY would belong to the last SELECT.