> 💡 모든 토글을 열고 닫는 단축키 Windows : Ctrl + alt + t
Join 이란 ?
- 👉 Join이란? 두 테이블의 공통된 정보 (key값)를 기준으로 테이블을 연결해서 한 테이블처럼 보는 것을 의미해요.무언가 연결된 정보가 있을 때, user_id 처럼 동일한 이름과 정보가 담긴 필드를 두 테이블에 똑같이 담아놓는답니다. 이런 필드를 두 테이블을 연결시켜주는 열쇠라는 의미로 'key'라고 불러요.
1.left join
어디에 -> 뭐를 붙일 건지, 순서가 중요하다.
2. inner join
예시)
select * from users u
inner join point_users p
on u.user_id = p.user_id;
많이 사용되는 join
*실습_1_order테이블에 users테이블 연결하기
select * from orders o inner join users u on o.user_id = u.user_id; |
👉 위 쿼리가 실행되는 순서: from → join → select
*실습_2_alias함께 사용하기 inner join
checkins 테이블에 courses 테이블 연결해서 통계치 내보기
select co.title, count(co.title) as checkin_count from checkins ci inner join courses co on ci.course_id = co.course_id group by co.title |
as -> alias를 사용하면 햇갈림을 줄일 수 있다.
*실습_3_order by 사용하기 inner join
point_users 테이블에 users 테이블 연결해서 순서대로 정렬해보기
select * from point_users p inner join users u on p.user_id = u.user_id order by p.point desc |
*실습_4_like사용해서 유사한 조건에 맞는 갯수 세어보기 inner join
select u.name, count(u.name) as count_name from orders o inner join users u on o.user_id = u.user_id where u.email like '%naver.com' group by u.name |
3. unoin - select를 여러번 해서가 아니라 한번에 두가지 타입 정보를 보고싶을 때 사용하기
아래처럼 두가지 select문을 쓰되, 가운데 union all을 사용하면 된다.단, union을 사용하면 내부정렬이 안되는 단점이 있다.
-> 이럴 땐 subquery를 사용한다.(4주차에 공부!)
(
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
)
'IT공부일지 > 개인학습 정리' 카테고리의 다른 글
경기도일자리재단 포토샵 강의 (0) | 2023.07.31 |
---|---|
포토샵 AI기능 100퍼 이용하기 (0) | 2023.07.23 |
SQL공부 일지_2주차(스파르타코딩클럽) (0) | 2022.08.03 |
SQL공부 일지_1주차(스파르타코딩클럽) (0) | 2022.07.28 |