MySQL
Unioni MySQL
Ricerca…
Sintassi
- SELECT nome_colonna FROM tabella1 UNION SELECT nome_colonna FROM tabella2;
- SELECT nome_colonna FROM tabella1 UNION ALL SELECT nome_colonna / i FROM tabella2;
- SELECT nome_colonna FROM tabella1 WHERE col_name = "XYZ" UNION ALL SELECT nome_colonna (s) FROM table2 WHERE col_name = "XYZ";
Osservazioni
UNION DISTINCT è uguale a UNION ; è più lento di UNION ALL causa di un passaggio di deduplicazione. Una buona pratica è sempre precisare DISTINCT o ALL , segnalando così che hai pensato a cosa fare.
Operatore dell'Unione
L'operatore UNION viene utilizzato per combinare il set di risultati ( solo valori distinti ) di due o più istruzioni SELECT.
Query: (per selezionare tutte le città diverse ( solo valori distinti ) dalle tabelle "Clienti" e "Fornitori")
SELECT City FROM Customers
UNION
SELECT City FROM Suppliers
ORDER BY City;
Risultato:
Number of Records: 10
City
------
Aachen
Albuquerque
Anchorage
Annecy
Barcelona
Barquisimeto
Bend
Bergamo
Berlin
Bern
Unione TUTTI
UNION ALL per selezionare tutte le città (anche i valori duplicati) dalle tabelle "Clienti" e "Fornitori".
Query:
SELECT City FROM Customers
UNION ALL
SELECT City FROM Suppliers
ORDER BY City;
Risultato:
Number of Records: 12
City
-------
Aachen
Albuquerque
Anchorage
Ann Arbor
Annecy
Barcelona
Barquisimeto
Bend
Bergamo
Berlin
Berlin
Bern
UNIONE TUTTO CON DOVE
UNION ALL per selezionare tutti (valori duplicati anche) città tedesche dalle tabelle "Clienti" e "Fornitori". Qui Country="Germany" deve essere specificato nella clausola where.
Query:
SELECT City, Country FROM Customers
WHERE Country='Germany'
UNION ALL
SELECT City, Country FROM Suppliers
WHERE Country='Germany'
ORDER BY City;
Risultato:
Number of Records: 14
| Città | Nazione |
|---|---|
| Aachen | Germania |
| Berlino | Germania |
| Berlino | Germania |
| Brandenburg | Germania |
| Cunewalde | Germania |
| Cuxhaven | Germania |
| Francoforte | Germania |
| Francoforte aM | Germania |
| Köln | Germania |
| Lipsia | Germania |
| Mannheim | Germania |
| München | Germania |
| Münster | Germania |
| Stoccarda | Germania |