본문 바로가기

SQL/LeetCode&HackerRank

[MySQL] Leetcode - 1045. Customers Who Bought All Products

문제: https://leetcode.com/problems/customers-who-bought-all-products/description/

 

나의 풀이:

select customer_id
from (
    select customer_id
        , count(distinct product_key) AS p_cnt
    from customer
    group by customer_id) sub
where p_cnt = (
    select count(distinct product_key)
    from product);

정답은 맞췄지만 뭔가... 돌아온 것 같아서 마음에 안 듦

그래서 솔루션을 보니

프롬절에 서브쿼리로 안 넣고 해빙으로 바로 조건 거는 방법이 있다

 

select customer_id
from customer
group by customer_id
having count(distinct product_key) = (
    select count(product_key)
    from product);

 

깔꼼~

그리고 프러덕트 테이블에서 프러덕트 키가 프라이머리 키여서 여기에서 디스팅트를 안 붙여줘도 된다!