https://school.programmers.co.kr/learn/courses/30/lessons/62284
코드설명
INNER JOIN + DISTINCT + GROUP BY + HAVING 를 활용합니다.
코드
아래코드는 비효율적으로 보입니다만, 가장 손쉽게 떠올릴 수 있는 방식이었습니다.
SELECT DISTINCT(CP.CART_ID)
FROM CART_PRODUCTS AS CP
INNER JOIN (SELECT DISTINCT(CART_ID) FROM CART_PRODUCTS WHERE NAME = 'MILK') AS CP2
ON CP.CART_ID = CP2.CART_ID
INNER JOIN (SELECT DISTINCT(CART_ID) FROM CART_PRODUCTS WHERE NAME = 'YOGURT') AS CP3
ON CP.CART_ID = CP3.CART_ID
ORDER BY CP.CART_ID ASC
혹은 GROUP BY 로도 가능합니다.
SELECT CP.CART_ID
FROM CART_PRODUCTS AS CP
INNER JOIN (SELECT DISTINCT(CART_ID) FROM CART_PRODUCTS WHERE NAME = 'MILK') AS CP2
ON CP.CART_ID = CP2.CART_ID
INNER JOIN (SELECT DISTINCT(CART_ID) FROM CART_PRODUCTS WHERE NAME = 'YOGURT') AS CP3
ON CP.CART_ID = CP3.CART_ID
GROUP BY CP.CART_ID
ORDER BY CP.CART_ID ASC
아래의 코드는 우선 'milk'와, 'yogurt' 가진 레코드를 모두 가져온뒤, cart_id로 그룹화하고 count(distinct name) 으로 값을 처리합니다.
SELECT CART_ID
FROM CART_PRODUCTS
WHERE NAME IN ('Milk', 'Yogurt')
GROUP BY CART_ID
HAVING COUNT(DISTINCT NAME) = 2
ORDER BY CART_ID ASC
ORACLE
-- 코드를 입력하세요
SELECT DISTINCT(CP.CART_ID)
FROM CART_PRODUCTS CP
WHERE EXISTS ( SELECT 1 FROM CART_PRODUCTS WHERE REGEXP_LIKE(NAME, 'MILK', 'i') AND CP.CART_ID = CART_ID )
AND EXISTS( SELECT 1 FROM CART_PRODUCTS WHERE REGEXP_LIKE(NAME, 'YOGURT', 'i') AND CP.CART_ID = CART_ID)
ORDER BY CP.CART_ID ASC
더 개선된 코드입니다.
SELECT CP.CART_ID
FROM CART_PRODUCTS CP
WHERE CP.NAME IN ('Milk', 'Yogurt')
GROUP BY CART_ID
HAVING COUNT(DISTINCT CP.NAME) >= 2
ORDER BY CP.CART_ID ASC