pbj0812의 코딩 일기

[SQL] MySQL 에서 FULL JOIN 본문

ComputerLanguage_Program/SQL

[SQL] MySQL 에서 FULL JOIN

pbj0812 2021. 2. 3. 02:40

0. 목표

 - MySQL 에서 FULL JOIN

1. 실습

 1) 테이블 생성

  - like

CREATE TABLE sql_test.like 
(
	ID INT,
	LikeDate datetime
);

  - buy

CREATE TABLE sql_test.buy 
(
	ID INT,
	BuyDate datetime
);

 2) 데이터 삽입

INSERT INTO sql_test.like(ID, LikeDate) VALUES(1, '2021-01-01');
INSERT INTO sql_test.like(ID, LikeDate) VALUES(1, '2021-01-02');
INSERT INTO sql_test.like(ID, LikeDate) VALUES(2, '2021-01-03');
INSERT INTO sql_test.like(ID, LikeDate) VALUES(2, '2021-02-04');
INSERT INTO sql_test.like(ID, LikeDate) VALUES(3, '2021-01-05');

INSERT INTO sql_test.buy(ID, BuyDate) VALUES(1, '2021-01-06');
INSERT INTO sql_test.buy(ID, BuyDate) VALUES(1, '2021-02-07');
INSERT INTO sql_test.buy(ID, BuyDate) VALUES(2, '2021-01-08');
INSERT INTO sql_test.buy(ID, BuyDate) VALUES(2, '2021-01-09');
INSERT INTO sql_test.buy(ID, BuyDate) VALUES(4, '2021-01-10');

 3) 데이터 확인

  - like

SELECT * FROM sql_test.like;

  - buy

SELECT * FROM sql_test.buy;

 4) UNION 을 사용한 FULL JOIN

SELECT * FROM sql_test.like
LEFT JOIN sql_test.buy 
ON sql_test.like.ID = sql_test.buy.ID

UNION 

SELECT * FROM sql_test.like
RIGHT JOIN sql_test.buy 
ON sql_test.like.ID = sql_test.buy.ID;

 5) UNION ALL 을 사용한 FULL JOIN

SELECT * FROM sql_test.like
LEFT JOIN sql_test.buy 
ON sql_test.like.ID = sql_test.buy.ID

UNION ALL

SELECT * FROM sql_test.like
RIGHT JOIN sql_test.buy 
ON sql_test.like.ID = sql_test.buy.ID;

2. 참고

 - MySQL에서 FULL OUTER JOIN 하는 방법?

Comments