MySQL(3) Join

2022. 9. 5. 01:46MySQL

Join이란?

두 테이블의 공통된 정보 (key값)를 기준으로 테이블을 연결해서 한 테이블처럼 보는 것을 의미.

예) user_id 필드를 기준으로 users 테이블과 orders 테이블을 연결해서 한 눈에 보고 싶어요!

select o.payment_method , ROUND(avg(p.point))  FROM point_users p
inner join orders o on p.user_id = o.user_id
GROUP BY o.payment_method

point_users 테이블 user_id로 orders를 inner join 하고
orders의 payment_method 그룹별로 묶고
orders의 payment_method 와 point_users의 point의 평균값을 보여줘.

 

위 쿼리의 결과

 

SELECT c.title , c2.week , count(*) as cnt FROM courses c 
inner join checkins c2 on c.course_id  = c2.course_id
GROUP BY c.title ,c2.week  
order by c.title ,c2.week

courses 테이블 course_id로 checkins를 inner join 하고

courses의 title, checkins의 week으로 그룹별로 묶고 정렬하고

courses의 title, checkins의 week을 보여주고 이를 카운트한 것을 보여줘

 

위 쿼리의 결과

 

SELECT c.title , c2.week , count(*) as cnt FROM courses c 
inner join checkins c2 on c.course_id = c2.course_id 
inner join orders o on c2.user_id  = o.user_id 
where o.created_at >= '2020-08-01'
group by c.title, c2.week
order by c.title, c2.week

courses 테이블 course_id로 checkins를 inner join 하고
checkins 테이블 user_id로 orders를 inner join 하고
orders의 created_at가 2020-08-01 이상인 것을
courses의 title, checkins의 week으로 그룹별로 묶고 정렬하고
courses의 title, checkins의 week을 보여주고 이를 카운트한 것을 보여줘

 

 

 

SELECT * from users u 
left join point_users pu on u.user_id = pu.user_id

498개 결과

 

SELECT * from users u 
inner join point_users pu on u.user_id = pu.user_id

271개 결과

 

left join 의 경우 일단 users 를 기준으로 두고 교집합을 추가하여 보여주는 것이기 때문에

users의 498개 결과가 전부 나온다. 때문에  point가 없는 user의 경우 null로 표시된다.

inner join 의 경우 두 테이블의 교집합을 보여주는 것이기 때문에

point_users , 즉 users 중 point를 갖고있는 유저만 보여주기 때문에 point_users의 271개 결과만 나온다.

user_id를 기준으로 보면 users에 point_users가 포함되는 듯.

WHERE pu.user_id IS NOT NULL , 

WHERE pu.user_id IS NULL 

조건을 붙여서 확인한 갯수를 더하면 271, 227 개로 498개가 맞아 떨어짐.

문제.

7월10일 ~ 7월19일에 가입한 고객 중, 포인트를 가진 고객의 숫자, 그리고 전체 숫자, 그리고 비율을 보고 싶어요!

아래와 같은 결과를 보고 싶다면 어떻게 해야할까요?

😉 count 는 NULL을 세지 않는다.

select count(point_user_id) as pnt_user_cnt,
       count(*) as tot_user_cnt, 
       round(count(point_user_id)/count(*),2) as ratio
  from users u
  left join point_users pu on u.user_id = pu.user_id
 where u.created_at between '2020-07-10' and '2020-07-20'

 

'MySQL' 카테고리의 다른 글

MySQL 그룹(GROUP BY), 정렬(ORDER BY)  (0) 2022.08.22
MySQL 기본 개념(1)  (0) 2022.08.22
MySQL 쓰는 이유  (0) 2022.08.22