• OUTER JOIN(LEFT JOIN, RIGHT JOIN) : 기준 테이블에만 데이터가 존재하면 조회됨
  • INNER JOIN : 기준 테이블과 조인 테이블 모두 데이터가 존재해야 조회됨

 

1. LEFT JOIN

테이블A를 중심으로 테이블B를 연결한다.

A의 값은 전부 표시하고 해당되는 값이 B에 없으면 NULL로 채운다.

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

LEFT JOIN

2. INNER JOIN

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

INNER JOIN

3. UNION

UNION이란? 2개 이상 테이블에 존재하는 같은 성격의 값을 하나의 쿼리로 추출하는 것

UNION - 중복되지 않은 값만 추출

UNION ALL - 중복 허용하고 모든 값 추출

(
	select '7월' as month, c1.title, c2.week, count(*) as cnt from courses c1
	inner join checkins c2 on c1.course_id = c2.course_id
	inner join orders o on c2.user_id = o.user_id
	where o.created_at < '2020-08-01'
	group by c1.title, c2.week
	order by c1.title, c2.week
)
union all
(
	select '8월' as month, c1.title, c2.week, count(*) as cnt from courses c1
	inner join checkins c2 on c1.course_id = c2.course_id
	inner join orders o on c2.user_id = o.user_id
	where o.created_at >= '2020-08-01'
	group by c1.title, c2.week
	order by c1.title, c2.week
)

union all에는 각각의 order by가 안먹기 때문에 위 쿼리에서 order by를 지워도 값이 똑같다.

union all한 전체에 order by를 걸어야 정렬이 된다.

 

'SQL' 카테고리의 다른 글

MySQL 접속  (0) 2023.06.14
실전에서 유용한 SQL 문법 (문자열, Case)  (0) 2023.05.04
SQL 4주차 - Subquery  (0) 2023.05.04
SQL 2주차 - GROUP BY, ORDER BY  (0) 2023.05.04
SQL 1주차 - BETWEEN, IN, LIKE, LIMIT  (0) 2023.04.27

1. 범위 조건

7월 13일, 7월 14일의 주문데이터만 뽑기

select * from orders
where created_at between "2020-07-13" and "2020-07-15";

 

 

2. 포함 조건

1, 3주차 사람들의 '오늘의 다짐' 데이터

select * from checkins 
where week in (1, 3);

 

3. 패턴(문자열 규칙)

select * from users 
where email like '%daum.net';
  • like 뒤에 나오는 %는 뭐가 나오든 상관 없다는 뜻

4. 일부만 가져오기 

limit 출력할 데이터 개수

select * from orders where payment_method = "kakaopay" limit 5;

 

'SQL' 카테고리의 다른 글

MySQL 접속  (0) 2023.06.14
실전에서 유용한 SQL 문법 (문자열, Case)  (0) 2023.05.04
SQL 4주차 - Subquery  (0) 2023.05.04
SQL 2주차 - GROUP BY, ORDER BY  (0) 2023.05.04
SQL 3주차 - JOIN, UNION  (0) 2023.05.02

+ Recent posts