[SQL] 2022-01-19

HyunWoo Cheon·2022년 1월 19일
  1. SQL과 데이터베이스 살펴보기
    1) Select 쿼리문의 개념
    쿼리(Query)문이란? 쿼리는 질의를 의미.
    데이터베이스에 명령을 내리는 것을 의미.
    여기서 Select 쿼리문은,
    데이터베이스에서 '데이터를 선택해서 가져오겠다'는 의미.
    2) 테이블과 필드
    • 테이블: orders라는 엑셀 시트.
      테이블은 데이터가 담긴 엑셀 시트와 동일.
      이런 형태의 값이 데이터베이스에 담기면,
      orders라는 이름의 테이블.
    • 필드: order_no, created_at, course_title, user_id, payment_method, email 각각이 필드.

orders 테이블의 데이터 가져와보기
select * from orders

orders 테이블의 특정 필드만 가져와보기
select created_at, course_title, payment_method, email from orders

  1. Select, Where 절 등 문법 연습해보기
    1) Where 절의 개념
    Where 절은, Select 쿼리문으로 가져올 데이터에 조건을 걸어주는 것을 의미 select * from orders
    where payment_method = 'kakaopay' Q) 잠깐! 왜 kakaopay가 아니라 'kakaopay'라고 쓰나요?
    A) kakaopay를 필드명이나 테이블명이 아닌 문자열로 인식시키려는거에요. select * from orders
    where course_title = '앱개발 종합반'
    and payment_method = 'kakaopay'2) Select 쿼리문에 Where 절 함께 써보기 연습 포인트가 20000점보다 많은 유저만 뽑아보기!
    select * from point_users
    where point > 20000 성이 황씨인 유저만 뽑아보기
    select * from users
    where name = '황**' 웹개발 종합반이면서 결제수단이 CARD인 주문건만 뽑아보기!
    select * from orders
    where course_title = '웹개발 종합반' and payment_method = 'CARD' 3) Tips!
    a. show tables로 어떤 테이블이 있는지 살펴보기
    b. 제일 원하는 정보가 있을 것 같은 테이블에
    select from 테이블명 쿼리 날려보기
    c. 원하는 정보가 없으면 다른 테이블에도 b.를 해보기
    d. 테이블을 찾았다! 조건을 걸 필드를 찾기
    e. select
    from 테이블명 where 조건 이렇게 쿼리 완성! 4) Where 절과 자주 같이쓰는 문법 배우기
    a. '같지 않음' 조건은 != 로.
    select * from orders
    where course_title != '웹개발 종합반'
      '!=' 에서 ! (느낌표)는 부정 (not)을 의미합니다.
      '='는 같음을 의미하니, '!='는 같지 않음이겠죠!
      

_ b. '범위' 조건은 between 으로.
select * from orders
where created_at between '2020-07-13' and '2020-07-15'

_ c. '포함' 조건은 in 으로.
select * from checkins
where week in (1, 3)

_ d. '패턴' 조건은 like 으로.
select * from users
where email like '%daum.net'

5) 일부 데이터만 가져오기: Limit
테이블에 어떤 데이터가 들어있나 잠깐 보려고 들어왔는데,
데이터를 다 불러오느라 시간이 오래 걸리면?
select * from orders
where payment_method = 'kakaopay'
limit 5

6) 중복 데이터는 제외하고 가져오기: Distinct
select distinct(payment_method) from orders

7) 몇 개인지 숫자 세보기: Count
select count(*) from orders

8) [응용] Distinct와 Count를 같이 써보기
SELECT count(distinct(name)) from users

  1. Quiz
    1) Gmail을 사용하는 2020/07/12~13에 가입한 유저를 추출하기
    select * from users
    where created_at between '2020-07-12' and '2020-07-14'
    and email like '%gmail.com'2) Gmail을 사용하는 2020/07/12~13에 가입한 유저의 수를 세기
    select count(*) from users
    where created_at between '2020-07-12' and '2020-07-14'
    and email like '%gmail.com'3) naver 이메일을 사용하면서, 웹개발 종합반을 신청했고 결제는 kakaopay로 이뤄진 주문데이터 추출하기
    select * from orders
    where email like '%naver.com'
    and course_title = '웹개발 종합반'
    and payment_method = 'kakaopay'
profile
I'm one and only.

0개의 댓글