[Programmers] SQL - 우유와 요거트가 담긴 장바구니

DMIS·2022년 3월 9일
0

SQL

목록 보기
26/48
post-thumbnail

문제

풀이

처음에는 cart_id를 기준으로 group by 절을 사용하여 테이블을 만들고 group_concat을 이용하여 다음과 같이 풀어보려 했다.

select cart_id from (select cart_id, group_concat(name) as name
from cart_products
group by cart_id
where name ilike '%milk%' and name ilike '%yogurt%')
order by cart_id

위와 같이 입력하고 제출하니 where 절에서 오류가 났다. 왜 오류가 났는지는 아직 모르겠다.


그래서 where 절을 두 번 사용하여 단순하게 풀었다.

select cart_id from cart_products
where cart_id in 
    (select cart_id from cart_products
     where name = 'Milk')
     and name = 'Yogurt'
order by cart_id

풀고나서 생각해보니 우유를 구매한 테이블과 요거트를 구매한 테이블을 각각 하나씩 만들어서 join을 통해 푸는 것도 나쁘지 않은 것 같다고 생각하여 다음과 같이 풀어보았다.

select t4.cart_id 
from (select t1.cart_id, t1.name 
      from cart_products as t1
      where t1.name = 'Milk') as t2
join (select t3.cart_id, t3.name 
      from cart_products as t3
      where t3.name = 'Yogurt') as t4
on t2.cart_id = t4.cart_id
order by t4.cart_id
profile
Data + Math

0개의 댓글