728x90
join
2개의 테이블을 하나로 합치는 방법
select *
from orders
join customers
on orders.customer_id = customers.id ;
-- 위 코드와 똑같은데 줄이는 방법
select *
from orders as o
join customers as c
on o.customer_id = c.id ;
-- 더 줄이는 방법
select *
from orders o
join customers c
on o.customer_id = c.id ;

결과는 3코드 전부 위 사진과 같습니다.
outer join
-- 모든 고객 데이터를 기준으로, 주문 정보를 붙여주세요.
-- 어떤 고객은 주문을 안 했는지 확인이 가능함.
select *
from customers c
left join orders o
on o.customer_id = c.id;

-- 각 고객별로, 주문수를 나타내시오.
select concat(c.first_name,' ',c.last_name) as customer_full_name ,count(o.id) as order_count
from customers c
left join orders o
on o.customer_id = c.id
group by c.id;

응용 )
각 요구사항에 맞춰서 간단한 문제풀이를 진행해보겠습니다.
-- 주문 금액이 600달러보다 큰 사람들한테, 프로모션 이메일을 보내려고한다.
-- 600달러보다 큰 사람들의 이메일을 가져오시오.
select distinct c.email -- email은 중복되는 데이터들이 있기 때문에 유니크한 값들만 조회.
from customers c
right join orders o
on o.customer_id = c.id
where o.amount > 600;

-- 각 고객별로 주문 금액 평균이 300달러 이상인 사람의 이름과, 평균금액을 가져오시오.
select c.first_name,c.last_name,avg(o.amount) as amount
from customers c
join orders o
on o.customer_id = c.id
group by c.id having amount > 300; -- group by의 having을 사용하여 요구사항 충족

-- 2019년 12월 20일부터 2020년 1월 10일 사이의 주문데이터에서,
-- 고객별 주문금액이 평균 300달러 이상 되는 사람의
-- 이름과, 평균주문금액을 표시하고, 평균 주문 금액이 높은 순서대로 보여주시오.
select concat(c.first_name,' ',c.last_name),avg(o.amount) as avg_amount
from customers c
left join orders o
on o.customer_id = c.id
where o.order_date between '2019-12-20' and '2020-01-10' -- 2019년12월20일~2020년1월10일 사이의 주문데이터
group by o.id having avg_amount >= 300 -- 고객별 주문 평균 금액이 300달러 이상인 데이터
order by avg_amount desc; -- 내림차순으로 정렬

'MySQL' 카테고리의 다른 글
MySQL - join , outer join 실습문제풀이 (0) | 2022.12.08 |
---|---|
MySQL - ifnull()함수 null을 다른 값으로 대체하는 방법 (0) | 2022.12.08 |
MySQL - foreign keys 설정하기 (0) | 2022.12.08 |
MySQL - case문과 if함수 사용하기 / 조건문 (0) | 2022.12.07 |
MySQL - group by에서 Having을 사용하는 방법 (0) | 2022.12.07 |