In Oracle Database, il UNION operatore ci consente di combinare i risultati di due query in un unico set di risultati.
Esempio
Supponiamo di avere le seguenti tabelle:
SELECT * FROM Teachers;
SELECT * FROM Students; Risultato:
| INSEGNANTE | NOME INSEGNANTE |
|---|---|
| 1 | Warren |
| 2 | Ben |
| 3 | Cathy |
| 4 | Cathy |
| 5 | Fattura |
| 6 | Fattura |
| STUDENTID | STUDENTNAME |
|---|---|
| 1 | Fai |
| 2 | Jet |
| 3 | Punta |
| 4 | In |
| 5 | Warren |
| 6 | Fattura |
Ecco un esempio di utilizzo di UNION operatore per restituire i nomi di tutti i docenti e studenti:
SELECT TeacherName FROM Teachers
UNION
SELECT StudentName FROM Students; Risultato:
| NOME INSEGNANTE |
|---|
| Ben |
| Fattura |
| Cathy |
| Ein |
| Fai |
| Jet |
| Punta |
| Warren |
Per impostazione predefinita, il UNION l'operatore applica implicitamente un DISTINCT operazione. In altre parole, restituisce solo valori distinti per impostazione predefinita. Quindi i risultati di cui sopra contengono solo uno ciascuno di Warren, Cathy e Bill. Questo nonostante il fatto che le tabelle combinate contengano effettivamente due Warren, due Cathy e tre Bill (ci sono due insegnanti chiamate Cathy, un'insegnante e un cliente chiamato Warren, e due chiamate Bill, oltre a uno studente chiamato Bill).
Includi duplicati
Possiamo usare il ALL parola chiave per includere valori duplicati nei risultati:
SELECT TeacherName FROM Teachers
UNION ALL
SELECT StudentName FROM Students; Risultato:
| NOME INSEGNANTE |
|---|
| Warren |
| Ben |
| Cathy |
| Cathy |
| Fattura |
| Fattura |
| Fai |
| Jet |
| Punta |
| Ein |
| Warren |
| Fattura |
Questa volta abbiamo ottenuto dodici righe invece delle otto che abbiamo ottenuto nel nostro primo esempio.
Possiamo vedere che entrambi i Cathy sono stati restituiti e tutti e tre i Bill sono stati restituiti.
Alcune cose da ricordare
Si noti che le espressioni devono corrispondere in numero e devono trovarsi nello stesso gruppo di tipi di dati. Pertanto, non possiamo fare quanto segue:
SELECT TeacherName FROM Teachers
UNION
SELECT StudentId, StudentName FROM Students; Risultato:
ORA-01789: query block has incorrect number of result columns
O questo:
SELECT TeacherName FROM Teachers
UNION
SELECT StudentId FROM Students; Risultato:
ORA-01790: expression must have same datatype as corresponding expression
Tuttavia, possiamo usare funzioni come TO_CHAR() per convertire una colonna in un gruppo di tipi di dati adatto:
SELECT TeacherName FROM Teachers
UNION
SELECT TO_CHAR(StudentId) FROM Students; Risultato:
TEACHERNAME 1 2 3 4 5 6 Ben Bill Cathy Warren