두 테이블에 모두 매치되는 값을 가진 rows를 리턴함.
[코드]
SELECT * FROM TableA A
INNER JOIN TableB B ON A.key = B.key
왼쪽 테이블의 모든 rows를 리턴하고, 오른쪽 테이블에서는 왼쪽 테이블에 매치되는 rows를 리턴함.
[코드]
SELECT * FROM TableA A
LEFT JOIN TableB B ON A.key = B.key
오른쪽 테이블의 모든 rows를 리턴하고, 왼쪽 테이블에서는 오른쪽 테이블에 매치되는 rows를 리턴함.
[코드]
SELECT * FROM TableA A
RIGHT JOIN TableB B ON A.key = B.key
왼쪽 테이블 혹은 오른쪽 테이블에 매치되는 모든 rows를 리턴함.
[코드]
SELECT * FROM TableA A
FULL OUTER JOIN TableB B ON A.key = B.key
[테이블 생성 및 값 삽입]
CREATE TABLE Students(StudentId integer, Name varchar(100));
INSERT INTO Students(StudentId, Name) values(1, "Ted"), (2, "Lily"), (3, "Marshall");
CREATE TABLE Scores(ScoreId integer, StudentId integer, Math integer, English integer);
INSERT INTO Scores(ScoreId, StudentId, Math, English) values(1, 1, 90, 95), (2, 2, 80, 100), (4, NULL, 75, 100);
<Student 테이블>
StudentId | Name |
---|---|
1 | Ted |
2 | Lily |
3 | Marshall |
<Score 테이블>
ScoreId | StudentId | Math | English |
---|---|---|---|
1 | 1 | 90 | 95 |
2 | 2 | 80 | 100 |
4 | NULL | 75 | 100 |
[코드]
SELECT st.StudentId
, st.name
, sc.math
, sc.english
FROM Student AS st
INNER JOIN Score AS sc ON st.StudentId = sc.StudentId;
[결과]
StudentId | name | math | english |
---|---|---|---|
1 | Ted | 90 | 95 |
2 | Lily | 80 | 100 |
[코드]
SELECT st.StudentId
, st.name
, sc.math
, sc.english
FROM Student AS st
LEFT JOIN Score AS sc ON st.StudentId = sc.StudentId;
[결과]
StudentId | name | math | english |
---|---|---|---|
1 | Ted | 90 | 95 |
2 | Lily | 80 | 100 |
3 | Marshall | NULL | NULL |
[코드]
SELECT st.StudentId
, st.name
, sc.math
, sc.english
FROM Student AS st
RIGHT JOIN Score AS sc ON st.StudentId = sc.StudentId;
[결과]
StudentId | name | math | english |
---|---|---|---|
1 | Ted | 90 | 95 |
2 | Lily | 80 | 100 |
NULL | NULL | 75 | 100 |
[코드]
SELECT st.StudentId
, st.name
, sc.math
, sc.english
FROM Student AS st
FULL OUTER JOIN Score AS sc ON st.StudentId = sc.StudentId;
[결과]
StudentId | Name | Math | English |
---|---|---|---|
1 | Ted | 90 | 95 |
2 | Lily | 80 | 100 |
NULL | NULL | 75 | 100 |
3 | Marshall | NULL | NULL |
⚠️ 주의 : MySQL에서는 FULL OUTER JOIN을 제공하지 않음.
MySQL에서는 다음과 같은 코드로 FULL OUTER JOIN를 구현할 수 있음.
[코드]
SELECT *
FROM Student AS st
LEFT JOIN Score AS sc ON st.StudentId = sc.StudentId
UNION
SELECT *
FROM Student AS st
RIGHT JOIN Score AS sc ON st.StudentId = sc.StudentId;
[결과]
StudentId | Name | ScoreId | StudentId | Math | English |
---|---|---|---|---|---|
1 | Ted | 1 | 1 | 90 | 95 |
2 | Lily | 2 | 2 | 80 | 100 |
3 | Marshall | NULL | NULL | NULL | NULL |
NULL | NULL | 4 | NULL | 75 | 100 |
참고:
https://www.w3schools.com/sql/sql_join.asp
https://sql-joins.leopard.in.ua/
MySQL online editor: https://paiza.io/en/projects/new?language=mysql
PostgreSQL online editor: https://extendsclass.com/postgresql-online.html