코드 그라데이션
[얄코] MySQL Section 2-1 쿼리 안의 서브쿼리 본문
1. 비상관 서브쿼리
1)
SELECT
CategoryID, CategoryName, Description,
(SELECT ProductName FROM Products WHERE ProductID = 1)
FROM Categories;
실행 결과
2)
SELECT * FROM Products
WHERE Price < (
SELECT AVG(Price) FROM Products
);
실행 결과
3)
SELECT
CategoryID, CategoryName, Description
FROM Categories
WHERE
CategoryID =
(SELECT CategoryID FROM Products
WHERE ProductName = 'Chais');
실행 결과
4)
SELECT
CategoryID, CategoryName, Description
FROM Categories
WHERE
CategoryID IN
(SELECT CategoryID FROM Products
WHERE Price > 50);
실행 결과
연산자 | 의미 |
~ ALL | 서브쿼리의 모든 결과에 대해 ~하다 |
~ANY | 서브쿼리의 하나 이상의 결과에 대해 ~하다 |
1)
SELECT * FROM Products
WHERE Price > ALL (
SELECT Price FROM Products
WHERE CategoryID = 2
);
실행 결과
2)
SELECT
CategoryID, CategoryName, Description
FROM Categories
WHERE
CategoryID = ANY
(SELECT CategoryID FROM Products
WHERE Price > 50);
실행 결과
2. 상관 서브쿼리
1)
SELECT
ProductID, ProductName,
(
SELECT CategoryName FROM Categories C
WHERE C.CategoryID = P.CategoryID
) AS CategoryName
FROM Products P;
실행 결과
2)
SELECT
SupplierName, Country, City,
(
SELECT COUNT(*) FROM Customers C
WHERE C.Country = S.Country
) AS CustomersInTheCountry,
(
SELECT COUNT(*) FROM Customers C
WHERE C.Country = S.Country
AND C.City = S.City
) AS CustomersInTheCity
FROM Suppliers S;
실행 결과
3)
SELECT
CategoryID, CategoryName,
(
SELECT MAX(Price) FROM Products P
WHERE P.CategoryID = C.CategoryID
) AS MaximumPrice,
(
SELECT AVG(Price) FROM Products P
WHERE P.CategoryID = C.CategoryID
) AS AveragePrice
FROM Categories C;
실행 결과
4)
SELECT
ProductID, ProductName, CategoryID, Price
-- ,(SELECT AVG(Price) FROM Products P2
-- WHERE P2.CategoryID = P1.CategoryID)
FROM Products P1
WHERE Price < (
SELECT AVG(Price) FROM Products P2
WHERE P2.CategoryID = P1.CategoryID
);
실행 결과
EXISTS / NOT EXISTS 연산자
SELECT
CategoryID, CategoryName
-- ,(SELECT MAX(P.Price) FROM Products P
-- WHERE P.CategoryID = C.CategoryID
-- ) AS MaxPrice
FROM Categories C
WHERE EXISTS (
SELECT * FROM Products P
WHERE P.CategoryID = C.CategoryID
AND P.Price > 80
);
실행 결과
728x90
'Java > 알고리즘' 카테고리의 다른 글
[Lv.0] 카운트 업 (0) | 2023.06.12 |
---|---|
[얄코] MySQL 2-2. JOIN : 여러 테이블 조립하기 (0) | 2023.06.11 |
[Lv.0] 문자열 바꿔서 찾기 (0) | 2023.06.10 |
[Lv.0] 로그인 성공? (2) | 2023.06.10 |
[얄코] MySQL 1-4. 시간, 날짜 관련 함수들 (0) | 2023.06.09 |
Comments