: 큰 쿼리문 안에 들어가는 작은 쿼리문 (하위 쿼리)
select * from users u
where u.user_id in (select o.user_id from orders o
where o.payment_method = 'kakaopay');
1) from 실행: users 데이터를 가져와줌 ```
select c.checkin_id, c.user_id, c.likes,
(select avg(likes) from checkins c2
where c2.user_id = c.user_id) as avg_like_user
from checkins c;
```
1) 밖의 select * from 문에서 데이터를 한줄한줄 출력하는 과정에서
2) select 안의 subquery가 매 데이터 한줄마다 실행되는데
3) 그 데이터 한 줄의 user_id를 갖는 데이터의 평균 좋아요 값을 subquery에서 계산해서
4) 함께 출력해준다!
: 서브쿼리의 별칭을 만들어, 복잡한 코드를 가독성있게 만들어줌
with table1 as (
select course_id, count(distinct(user_id)) as cnt_checkins from checkins
group by course_id
), table2 as (
select course_id, count(*) as cnt_total from orders
group by course_id
)
select c.title,
a.cnt_checkins,
b.cnt_total,
(a.cnt_checkins/b.cnt_total) as ratio
from table1 a inner join table2 b on a.course_id = b.course_id
inner join courses c on a.course_id = c.course_id
SUBSTRING_INDEX(문자열, '기준 문자', 가져올 조각 순서)
SUBSTRING_INDEX(email, '@', 1)
substring(문자열,출력하고 싶은 첫 글자의 위치,출력할 글자 개수)
Case : 경우에 따라 원하는 값을 새 필드에 출력하기
case
when 문자열 조건 then 출력하려는 값
else 출력하려는 값
END
case
when point >= 5000 then '잘했어요'
else '노력합시다'
END
distinct : 중복없이 세기
distinct(항목)