UNION
SyntaxSELECT ... UNION [ALL] SELECT ... [UNION SELECT ...]
UNION
is implemented in MySQL 4.0.0.
UNION
is used to combine the result from many SELECT
statements into one result set.
The columns listed in the select_expression portion of the SELECT
should have the same type. The column names used in the first
SELECT
query will be used as the column names for the results
returned.
The SELECT
commands are normal select commands, but with the following
restrictions:
SELECT
command can have INTO OUTFILE
.
If you don't use the keyword ALL
for the UNION
, all
returned rows will be unique, as if you had done a DISTINCT
for
the total result set. If you specify ALL
, then you will get all
matching rows from all the used SELECT
statements.
If you want to use an ORDER BY
for the total UNION
result,
you should use parentheses:
(SELECT a FROM table_name WHERE a=10 AND B=1 ORDER BY a LIMIT 10) UNION (SELECT a FROM table_name WHERE a=11 AND B=2 ORDER BY a LIMIT 10) ORDER BY a;
Posted by David Ranney on Tuesday February 18 2003, @4:54pm | [Delete] [Edit] |
One little gotcha with UNION. The manual says that the
columns you select should be of the same type. That means
that if you SELECT literal values first, as you might if you wanted column headers to be printed, subsequent SELECTs
in the UNION will be limited to the lengths of strings you give.
Example:
If you run a SELECT statement such as this:
SELECT
"foo" foo_col,
"bar" bar_col,
"zama" zama_col
UNION ALL
SELECT
foo_col,
bar_col,
zama_col
FROM
tabname
...
The returned columns will be limited to 3, 3, and
4 characters in length respectively because that was
the length of the first "row" returned.
To workaround this, select an empty row from the
true table first:
SELECT
foo_col,
bar_col,
zama_col
FROM
tabname
WHERE
1=0
UNION
SELECT
"foo" foo_col,
"bar" bar_col,
"zama" zama_col
UNION ALL
SELECT
foo_col,
bar_col,
zama_col
FROM
...
Posted by Keith Ivey on Thursday May 8 2003, @1:10pm | [Delete] [Edit] |
It's not documented above, but you can use ORDER BY on a UNION that consists of only one SELECT (and thus doesn't actually include the word "UNION"). Suppose you want the last 5 entries in a table, but you want them in ascending order. You can use this query:
( SELECT * FROM table_name ORDER BY ranking DESC
LIMIT 5 ) ORDER BY ranking;
Similarly, you could select the top 10 records from a table ordered by one column and then sort them alphabetically by another column.
Posted by Michael Bailey on Monday July 7 2003, @3:01pm | [Delete] [Edit] |
If you are still working in MySQL 3.x and need to know how to emulate the UNION statement, here's a good article to check out:
http://jinxidoru.com/tutorials/union.html