데이터 베이스 3주차
join - 중요!!
: 두 테이블의 공통된 정보 (key값)를 기준으로 테이블을 연결해서 한 테이블처럼 보는 것
# enrolleds 테이블에 courses 테이블 연결해보기
select * from enrolleds e // 항상 from에 들어간 테이블을 기준으로, 다른 테이블이 붙는다고 생각하면 편함
inner join courses c
on e.course_id = c.course_id; // 두 테이블이 공유하는 항목으로 연결
// 실행순서 from → join → where → group by → select
select u.name, count(u.name) as count_name from orders o
inner join users u
on o.user_id = u.user_id // orders 테이블의 user_id와 '동일한' user_id를 갖는 users 테이블 데이터를 붙임
where u.email like '%naver.com'
group by u.name // users의 name별로
# 결제하고 시작하지 않은 유저들을 성씨별로 세어보기
select name, count(*) as cnt from enrolleds e // name으로 묶은 사람들의 전체를 출력, *를 name으로 바꿔도 결과는 같음
inner join users u
on e.user_id = u.user_id
where is_registered = 0 // is_registered 가 0인 사람들을
group by name // 성으로 묶기
order by cnt desc
select c1.title, c2.week, count(*) as cnt from courses c1
inner join checkins c2 on c1.course_id = c2.course_id // c1에 c2를 붙이고
inner join orders o on c2.user_id = o.user_id // c2에 o를 한번 더 붙임
where o.created_at >= '2020-08-01' // created_at 이 8월 이후인 사람들만
group by c1.title, c2.week // title과 week로 묶어줌
order by c1.title, c2.week // 오름차순 정렬
어떤 그룹 별로 보고 싶은게 아니라, 그냥 갯수만 출력하려면 group by를 안써줘도 됨.
반올림은 round(값, 소수점자리 수) -> round(count(*), 2) ; 전체의 반올림 2번째자리 까지
union
: 두 그룹을 한번에 모아서 보여줌
(
select '7월' as month, c.title, c2.week, count(*) as cnt from checkins c2 // '7월' as month로 열을 만들어줌
inner join courses c on c2.course_id = c.course_id
inner join orders o on o.user_id = c2.user_id
where o.created_at < '2020-08-01' // 7월에 만들어진 유저
group by c2.course_id, c2.week
)
union all // 서로 다른 쿼리를 작성한 후, union all을 통해 묶어줌.
(
select '8월' as month, c.title, c2.week, count(*) as cnt from checkins c2
inner join courses c on c2.course_id = c.course_id
inner join orders o on o.user_id = c2.user_id
where o.created_at > '2020-08-01' // 8월에 만들어진 유저
group by c2.course_id, c2.week
order by c2.course_id, c2.week
)
→ select 에 month를 추가해줌으로써 month열이 생김