UNION
Sintassi
SELECT ... UNION [ALL | DISTINCT] SELECT ... [UNION [ALL | DISTINCT] SELECT ...] [ORDER BY [colonna [, colonna ...]]] [LIMIT {[scarto,] num_righe | num_righe OFFSET scarto}]
Spiegazione
UNION
combina i risultati di più istruzioni SELECT
in un solo insieme di risultati.
I nomi delle colonne della prima SELECT
sono usati come nomi per tutto l'insieme dei risultati. Le colonne selezionate elencate nelle posizioni corrispondenti delle SELECT
successive dovrebbero avere gli stessi tipi di dati. Per esempio, la prima colonna selezionata nella prima istruzione dovrebbe essere dello stesso tipo della prima colonna selezionata nelle altre istruzioni.
La parola chiave ALL
fa sì che le righe duplicate siano preservate. La parola chiave DISTINCT
fa sì che le righe duplicate vengano rimosse dall'insieme dei risultati. Questo è anche il comportamento di default.
The ORDER BY
and LIMIT
clauses
Individual tables can contain their own ORDER BY
and LIMIT
clauses. In that case, the individual queries need to be wrapped between parenthesis. However, this does not affect the order of the UNION
, so they only are useful to limit the record read by one SELECT
.
The UNION
can have global ORDER BY
and LIMIT
clauses, which affect the whole resultset. If the columns retreived by individual SELECT
statements have an alias (AS
), the ORDER BY
must use that alias, not the real column names.
Examples
Defining the UNION
's global order and limiting total rows:
(SELECT e_name AS name, email FROM employees) UNION (SELECT c_name AS name, email FROM customers) ORDER BY name LIMIT 10;