기초 SQL 문법정리

나명흠·2023년 3월 10일
0

select절

   select * from orders

where절

   where course_title = "앱개발 종합반" and payment_method = "kakaopay";

where 조건 (table 값)
where절과 함께 쓰는 문법
!= 같지않음
btween ''and'' 범위 조건
like '~%~' 패턴 조건
in () 포함 조건
limit 숫자 수 만큼의 데이터만 불러오기
distinct 중복데이터 제외하기
count 숫자 세기

group by
범주별로 묶기

   select name, count(*) from users
   group by name;

order by
정렬하기 (기본 오름차순, desc 내림차순)

   group by name;

join
테이블 합치기
inner join 데이터 on 데이터
공통 부분으로 묶기

    select c.course_id, c.title, count(*) as cnt_notstart from courses c
    inner join enrolleds e 
    on c.course_id = e.course_id
    where is_registered = 0
    group by c.course_id

left join 데이터 on 데이터
기준이 되는 데이터에 붙기 때문에 비어있는 데이터에는 붙지 않음

    select * from users u
    left join point_users p
    on u.user_id = p.user_id;

subquery
쿼리문 안에 테이블이나 필드 값이 쿼리로 들어가는 경우
where에 들어가는 subquery

	select * from users u
	where u.user_id in (select o.user_id from orders o 
					where o.payment_method = 'kakaopay');

select에 들어가는 subquery

    select checkin_id, course_id, user_id, likes, 
    (select avg(c2.likes) from checkins c2
    where c.course_id = c2.course_id) 
    from checkins c;

from에 들어가는 subquery

      select c.title,
             a.cnt_checkins,
             b.cnt_total,
             (a.cnt_checkins/b.cnt_total) as ratio
      from
      (
          select course_id, count(distinct(user_id)) as cnt_checkins from 			  checkins
          group by course_id
      ) a
      inner join
      (
          select course_id, count(*) as cnt_total from orders
          group by course_id 
      ) b on a.course_id = b.course_id
      inner join courses c on a.course_id = c.course_id

with절
서브쿼리로 인해 복잡할 경우 이름붙여 정리

	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
특정 필드의 값을 '~'을 기준으로 나누는 것

	select user_id, email, SUBSTRING_INDEX(email, '@', 1) from users
    select user_id, email, SUBSTRING_INDEX(email, '@', -1) from users

case
조건에 따라 원하는 값을 새 필드에 출력

	select pu.point_user_id, pu.point,
    case 
    when pu.point > 10000 then '잘 하고 있어요!'
    else '조금 더 달려주세요!'
    END as '구분'
    from point_users pu;
profile
가보자고

0개의 댓글