1. Join의 종류
2. Join의 방식
3. Inner Join
쉽게말해 교집합이라고 생각하시면 됩니다.
기준 테이블과 Join 한 테이블의 중복된 값을 보여줍니다.
결과값은 A의 테이블과 B테이블이 모두 가지고 있는 데이터만 검색됩니다.
Join 문법
SELECT
테이블별칭.조회할칼럼,
테이블별칭.조회할칼럼
FROM 기준테이블 별칭
INNER JOIN 조인테이블 별칭 ON 기준테이블별칭.기준키 = 조인테이블별칭.기준키...
--예제--
SELECT
A.NAME, --A테이블의 NAME조회
B.AGE --B테이블의 AGE조회
FROM EX_TABLE A
INNER JOIN JOIN_TABLE B ON A.NO_EMP = B.NO_EMP AND A.DEPT = B.DEPT
4. Left Outer Join
기본 테이블의 값 + 테이블과 기준 테이블의 중복된 값을 보여줌.
왼쪽 테이블을 기준으로 JOIN 하겠다.
그럼 결괏값은 A 테이블의 모든 데이터와 A테이블과 B테이블의 중복되는 값이 검색됨.
4-1) Topic Table
4**-1)-1. Topic Table → topic_backup수정**
rename table topic to topic_backup;
Console
4**-1)-2. create topic table(테이블 생성)**
create table topic(
id int(11) not null, auto_increment,
title varchar(30) not null,
description text null,
created datetime not null,
author_id int(11) nll,
primary key(id)
);
Console
4-1)-3. Insert(테이터 삽입)
INSERT INTO topic (title, description, created, author_id)
values("MySQL", "MySQL is...", now(), "1");
Console
4-2) author(저자)를 별도의 표로 빼내기
4-2)-1. create author(테이블 생성)
CREATE author(
id int(11) not null auto_increment,
name varchar(30) not null,
profile varchar(200) null,
primary key(id)
);
Console
4-2)-2. insert (데이터 삽입)
INSERT INTO author (name, profile) values("egoing", "developer");
Console
4-3) table topic과 table author Join
table topic
table author
4-3)-1. Join
Join 문법
SELECT
테이블별칭.조회할칼럼,
테이블별칭.조회할칼럼
FROM 기준테이블 별칭
INNER JOIN 조인테이블 별칭 ON 기준테이블별칭.기준키 = 조인테이블별칭.기준키...
topic과 author을 Join하기 위한 결합고리는 ‘author_id’이고 2번에서는 ‘id’ 값임.
SELECT * FROM topic LEFT JOIN author
ON topic.author_id = author.id;
Console
4-3)-2. Join 후 데이터 조회
SELECT id, title, description, created, name, profile
FROM topic
LEFT JOIN author ON topic.author_id = author.id;
Console(Error)
ERROR 1052 (23000): Column 'id in filed list is ambiguous(모호함)
topic의 id -> topic.id로 수정
SELECT topic.id, title, description, created, name, profile
FROM topic LEFT JOIN author ON topic.author_id = author.id;
Console(Success)
4-3)-3. topic의 id를 별칭을 이용해 topic_id로 수정하기
SELECT topic.id AS topic_id, title, description, created, name, profile
FROM topic LEFT JOIN author ON topic.author_id = author.id;
Console(Success)
4-4) Comment table
4-4)-1. create Comment(테이블 생성)
4-4)-2. insert(데이터 삽입)
4-5) comment와 author Join
4-6) Join 맺은 테이블을 통해 table author 데이터 바꾸기