2021-12-03 16:31 작성
My SQL basic 메모
Table of contents
LEFT JOIN 심화 예시
1. 3개 tables 연결하기
다음 employees, customers 그리고 payments를 join 해보자:
SELECT
lastName,
firstName,
customerName,
checkNumber,
amount
FROM
employees
LEFT JOIN customers ON
employeeNumber = salesRepEmployeeNumber
LEFT JOIN payments ON
payments.customerNumber = customers.customerNumber
ORDER BY
customerName,
checkNumber;
output: 쿼리를 통해 현재 실적을 알 수도 있다.
| lastName | firstName | customerName | checkNumber | amount |
|---|---|---|---|---|
| Murphy | Diane | NULL | NULL | NULL |
| Patterson | Mary | NULL | NULL | NULL |
| Firrelli | Jeff | NULL | NULL | NULL |
| Patterson | William | NULL | NULL | NULL |
| Bondur | Gerard | NULL | NULL | NULL |
| Bow | Anthony | NULL | NULL | NULL |
| King | Tom | NULL | NULL | NULL |
| Kato | Yoshimi | NULL | NULL | NULL |
| Hernandez | Gerard | Alpha Cognac | AF40894 | 33818.34 |
| Hernandez | Gerard | Alpha Cognac | HR224331 | 12432.32 |
| Hernandez | Gerard | Alpha Cognac | KI744716 | 14232.70 |
| Tseng | Foon Yue | American Souvenirs Inc | NULL | NULL |
| Castillo | Pamela | Amica Models & Co. | IJ399820 | 33924.24 |
| Castillo | Pamela | Amica Models & Co. | NE404084 | 48298.99 |
| Fixter | Andy | Anna’s Decorations, Ltd | EM979878 | 27083.78 |
| Fixter | Andy | Anna’s Decorations, Ltd | KM841847 | 38547.19 |
2. WHERE에서의 조건문 vs ON에서의 조건문
다음의 예시를 보자.
SELECT
o.orderNumber,
customerNumber,
productCode
FROM
orders o
LEFT JOIN orderdetails
USING (orderNumber)
WHERE
orderNumber = 10123;
output:
| orderNumber | customerNumber | productCode |
|---|---|---|
| 10123 | 103 | S18_1589 |
| 10123 | 103 | S18_2870 |
| 10123 | 103 | S18_3685 |
| 10123 | 103 | S24_1628 |
이 예시에서는 orderNumber가 10123인 항목만 추출한 것을 알 수 있다.
그러나 WHERE이 아닌 ON에서 조건을 추가하게 한다면:
SELECT
o.orderNumber,
customerNumber,
productCode
FROM
orders o
LEFT JOIN orderdetails d
ON o.orderNumber = d.orderNumber AND
o.orderNumber = 10123;
output:
| orderNumber | customerNumber | productCode |
|---|---|---|
| 10123 | 103 | S18_1589 |
| 10123 | 103 | S18_2870 |
| 10123 | 103 | S18_3685 |
| 10123 | 103 | S24_1628 |
| 10298 | 103 | NULL |
| 10345 | 103 | NULL |
| 10124 | 112 | NULL |
| 10278 | 112 | NULL |
| 10346 | 112 | NULL |
쿼리는 모든 orders table의 데이터를 가져오지만 10123을 가진 row만이 두 번째 table인 orderdetails의 productCode를 가지고 있을 것이다.
INNER JOIN의 경우ON에서 조건을 달거나WHERE에서 조건을 달거나 동일한 결과값을 반환하지만LEFT JOIN은 서로 다른 결과값을 반환한다는 점에 주목해야 한다.
RIGHT JOIN 심화 예시
LEFT JOIN의 역이므로 생략한다.
SELECT
employeeNumber,
customerNumber
FROM
customers
RIGHT JOIN employees ON
salesRepEmployeeNumber = employeeNumber
WHERE customerNumber is NULL
ORDER BY employeeNumber;
output:
| employeeNumber | customerNumber |
|---|---|
| 1002 | NULL |
| 1056 | NULL |
| 1076 | NULL |
| 1088 | NULL |
| 1102 | NULL |
| 1143 | NULL |
| 1619 | NULL |
| 1625 | NULL |