코드 그라데이션
[얄코] MySQL 2-2. JOIN : 여러 테이블 조립하기 본문
1. JOIN(INNER JOIN) - 내부 조인
- 양쪽 모두에 값이 있는 행(NOT NULL) 반환
- 'INNER' 은 선택사항
1)
SELECT * FROM Categories C
JOIN Products P
ON C.CategoryID = P.CategoryID;
실행 결과
2)
SELECT C.CategoryID, C.CategoryName, P.ProductName
FROM Categories C
JOIN Products P
ON C.CategoryID = P.CategoryID;
-- ambiguous 주의!
실행 결과
3)
SELECT
CONCAT(
P.ProductName, ' by ', S.SupplierName
) AS Product,
S.Phone, P.Price
FROM Products P
JOIN Suppliers S
ON P.SupplierID = S.SupplierID
WHERE Price > 50
ORDER BY ProductName;
실행 결과
여러 테이블을 조인 할 수 있다.
SELECT
C.CategoryID, C.CategoryName,
P.ProductName,
O.OrderDate,
D.Quantity
FROM Categories C
JOIN Products P
ON C.CategoryID = P.CategoryID
JOIN OrderDetails D
ON P.ProductID = D.ProductID
JOIN Orders O
ON O.OrderID = D.OrderID;
실행 결과
JOIN한 테이블 GROUP 하기
1)
SELECT
C.CategoryName,
MIN(O.OrderDate) AS FirstOrder,
MAX(O.OrderDate) AS LastOrder,
SUM(D.Quantity) AS TotalQuantity
FROM Categories C
JOIN Products P
ON C.CategoryID = P.CategoryID
JOIN OrderDetails D
ON P.ProductID = D.ProductID
JOIN Orders O
ON O.OrderID = D.OrderID
GROUP BY C.CategoryID;
실행 결과
2)
SELECT
C.CategoryName, P.ProductName,
MIN(O.OrderDate) AS FirstOrder,
MAX(O.OrderDate) AS LastOrder,
SUM(D.Quantity) AS TotalQuantity
FROM Categories C
JOIN Products P
ON C.CategoryID = P.CategoryID
JOIN OrderDetails D
ON P.ProductID = D.ProductID
JOIN Orders O
ON O.OrderID = D.OrderID
GROUP BY C.CategoryID, P.ProductID;
실행 결과
SELF JOIN - 같은 테이블끼리
SELECT
E1.EmployeeID, CONCAT_WS(' ', E1.FirstName, E1.LastName) AS Employee,
E2.EmployeeID, CONCAT_WS(' ', E2.FirstName, E2.LastName) AS NextEmployee
FROM Employees E1 JOIN Employees E2
ON E1.EmployeeID + 1 = E2.EmployeeID;
-- 1번의 전, 마지막 번호의 다음은?
실행 결과
3. CROSS JOIN - 교차 조인
- 조건 없이 모든 조합 반환(A * B)
SELECT
E1.LastName, E2.FirstName
FROM Employees E1
CROSS JOIN Employees E2
ORDER BY E1.EmployeeID;
728x90
'Java > 알고리즘' 카테고리의 다른 글
[Lv.0] 문자열의 앞의 n글자 (0) | 2023.06.14 |
---|---|
[Lv.0] 카운트 업 (0) | 2023.06.12 |
[얄코] MySQL Section 2-1 쿼리 안의 서브쿼리 (0) | 2023.06.10 |
[Lv.0] 문자열 바꿔서 찾기 (0) | 2023.06.10 |
[Lv.0] 로그인 성공? (2) | 2023.06.10 |
Comments