-
[3주차] SQL 3주차카테고리 없음 2022. 12. 22. 14:24
스파르타코딩클럽 내일배움단 '엑셀보다 쉬운 SQL'
주요 내용: 합치는건 join, 결과 연결은 union
* Alias 기능이 여기서 쓰인다!
[JOIN]
join을 할 때는 뭔가 하나 연결고리가 필요하다!= 공통 key 값이 필요함
- inner join은 교집합: 순서가 상관 없다. 모두 가지고 있는 데이터만 보여주니까!select * from users u inner join point_users p on u.user_id = p.user_id;- left join은 왼쪽에다 붙이는 것: 없으면 null로 보여준다. 즉, 순서가 상관 있다(어디에 무엇을 붙일 것이지가 중요).
select * from users u left join point_users p on u.user_id = p.user_id;(ex) 포인트가 있는 사람과 없는 사람을 구분 할 때
없으면 NULL 값이 뜬다.
where 절로 '~ is NULL' 혹은 '~is not NULL'로 조건을 지정해서 볼 수 있다.
select name, count(*) from users u left join point_users pu on u.user_id = pu.user_id where pu.point_user_id is NULL group by name- join 할 테이블이 여러개라면?
select c1.title, c2.week, count(*) as cnt from courses c1 inner join checkins c2 on c1.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 c1.title, c2.week order by c1.title, c2.week> inner join 을 2번 써주면 된다!
> select * from 테이블명 은 또 쓸 필요가 없다. 오류 난다.
> group by와 order by를 여러개로 설정하려면 ,(콤마)로 이을 수 있다. 오름차순 내림차순은 따로 정할 수 있다.
아래 코드 블럭처럼 뒤에 desc 붙이면 끝!
select c1.title, c2.week, count(*) as cnt from courses c1 inner join checkins c2 on c1.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 c1.title desc, c2.week order by c1.title, c2.week desc
[UNION]
- select를 두번하지 않고 모아서 보고 싶을 때!- union은 order by가 안먹힌다. 합친 곳에서 다시 order하는 방법을 사용해야 한다.
( select '7월' 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' group by c2.course_id, c2.week order by c2.course_id, c2.week ) 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' group by c2.course_id, c2.week order by c2.course_id, c2.week )> (위에 붙일 코드) union all (아래 붙일 코드)