Introduction à SQL Server
John MacKintosh
Instructor
LEFT et RIGHT ?LEFT et RIGHT ?Table des admissions
+------------+----------+
| Patient_ID | Admitted |
|------------+----------|
| 1 | 1 |
| 2 | 1 |
| 3 | 1 |
| 4 | 1 |
| 5 | 1 |
+------------+----------+
Table des sorties
+------------+------------+
| Patient_ID | Discharged |
|------------+------------|
| 1 | 1 |
| 3 | 1 |
| 4 | 1 |
+------------+------------+
JOINTURE INTERNE :
+------------+----------+------------|
| Patient_ID | Admitted | Discharged |
|------------+----------|------------|
| 1 | 1 | 1 |
| 3 | 1 | 1 |
| 4 | 1 | 1 |
+------------+----------+------------+
JOIN LEFT :
+------------+----------+------------|
| Patient_ID | Admitted | Discharged |
|------------+----------|------------|
| 1 | 1 | 1 |
| 2 | 1 | NULL |
| 3 | 1 | 1 |
| 4 | 1 | 1 |
| 5 | 1 | NULL |
+------------+----------+------------+
SELECT
Admitted.Patient_ID,
Admitted,
Discharged
FROM Admitted
LEFT JOIN Discharged ON Discharged.Patient_ID = Admitted.Patient_ID;
SELECT
Admitted.Patient_ID,
Admitted,
Discharged
FROM Admitted
LEFT JOIN Discharged ON Discharged.Patient_ID = Admitted.Patient_ID;
+------------+----------+------------|
| Patient_ID | Admitted | Discharged |
|------------+----------|------------|
| 1 | 1 | 1 |
| 2 | 1 | NULL |
| 3 | 1 | 1 |
| 4 | 1 | 1 |
| 5 | 1 | NULL |
+------------+----------+------------+
SELECT
Admitted.Patient_ID,
Admitted,
Discharged
FROM Discharged
RIGHT JOIN Admitted ON Admitted.Patient_ID = Discharged.Patient_ID;
SELECT
Admitted.Patient_ID,
Admitted,
Discharged
FROM Discharged
RIGHT JOIN Admitted ON Admitted.Patient_ID = Discharged.Patient_ID;
+------------+----------+------------|
| Patient_ID | Admitted | Discharged |
|------------+----------|------------|
| 1 | 1 | 1 |
| 2 | 1 | NULL |
| 3 | 1 | 1 |
| 4 | 1 | 1 |
| 5 | 1 | NULL |
+------------+----------+------------+
INNER JOIN : Renvoie uniquement les lignes correspondantesLEFT JOIN (ou RIGHT JOIN) : Toutes les lignes de la table principale ainsi que les correspondances de la table de jointureNULL : Affiché si aucune correspondance n'est trouvéeLEFT JOIN et RIGHT JOIN peuvent être interchangeablesIntroduction à SQL Server