SQL - Union

sung eon·2022년 5월 24일
0

SQL

목록 보기
6/15

select를 두번하고 싶을 때 어떻게 해야할까?

Union을 써준다.

노란색이 7월거, 파란색이 8월 거라면 이 두개를 같이 보고 싶을 때 Union을 쓸 수 있다.
대신, 그러려면 한 가지 조건이 있는데, 그건 바로
노란색 박스와 파란색 박스의 필드명이 같아야 한다!

우리가 배운걸로 할 수 있는 건, 8월 이후 체크인 된 사람들을 보여준 거에서,

여기서, title 필드 왼쪽에 month 필드를 추가하여 8월 이후 체크인된 것이라는 걸 보여주고 싶다.
그땐


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


select '8월' as month을 추가해 주면

month 필드가 추가되었다!
그럼 7월 거를 붙여보자.


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


7월을 8월 위로 올려주고 이렇게 () union all ()로 연결해주면,

(
	7월
)
union all
(
	8월
)

그러면 이렇게 나온다!

쨔란~~
근데 잠깐만, title, week 이쁘게 order 한게 깨져버렸다!
그 말은 즉, union 에서는 order가 안 먹힌다는 뜻.
그래서 order는 지워줘도 된다.
따라서 합치기 전에 order한거는 합친 후에 의미가 없어지므로, 합친 후에 다시 order를 해줘야 한다.
= subquery

만약 필드명이 다른걸 하나로 합치고 싶으면 as로 필드명 같게 강제로 만들어준다.
( select week as a from checkins c ) union all ( select is_registered as a from enrolleds e ) order by a desc

profile
코베베

0개의 댓글