In Oracle Database, il MINUS operatore viene utilizzato per restituire solo righe univoche restituite dalla prima query ma non dalla seconda.
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 |
| STUDENTIDO | STUDENTNAME |
|---|---|
| 1 | Fai |
| 2 | Jet |
| 3 | Punta |
| 4 | In |
| 5 | Warren |
| 6 | Fattura |
Possiamo usare il MINUS operatore per restituire gli insegnanti che non sono anche studenti:
SELECT TeacherName FROM Teachers
MINUS
SELECT StudentName FROM Students; Risultato:
| NOME INSEGNANTE |
|---|
| Ben |
| Cathy |
Quindi otteniamo solo i valori che appaiono in Teachers tabella che non compare anche in Students tavolo.
Possiamo ottenere risultati diversi, a seconda di quale tabella si trova a sinistra e quale a destra. Ecco un esempio che mette gli Students tabella a sinistra e Teachers a destra:
SELECT StudentName FROM Students
MINUS
SELECT TeacherName FROM Teachers; Risultato:
| STUDENTNAME |
|---|
| Ein |
| Fai |
| Jet |
| Punta |
Questa volta abbiamo studenti che non sono anche insegnanti.
Il MINUS l'operatore restituisce solo righe distinte. Quindi nel nostro esempio, viene restituita solo una riga per Cathy , anche se ci sono due insegnanti con quel nome.
Un'alternativa
È possibile ottenere lo stesso risultato senza utilizzare il MINUS operatore. Ad esempio, potremmo riscrivere il nostro primo esempio in questo:
SELECT
DISTINCT TeacherName
FROM Teachers t
WHERE NOT EXISTS (SELECT StudentName FROM Students s
WHERE t.TeacherName = s.StudentName); Risultato:
| NOME INSEGNANTE |
|---|
| Ben |
| Cathy |
MINUS Equivalenti in altri RDBMS
MINUS di Oracle l'operatore è simile a EXCEPT operatore utilizzato da molti altri RDBMS. MariaDB ha un EXCEPT operatore, ma ha anche introdotto un MINUS operatore come sinonimo che può essere utilizzato in modalità Oracle.