먹었으면 뇌를 쓰자

MySQL ④ 관계형 데이터베이스/테이블 분리/JOIN 본문

SQL

MySQL ④ 관계형 데이터베이스/테이블 분리/JOIN

뇌이비 2022. 10. 21. 21:52

관계형 데이터베이스

 

관계형 데이터베이스를 이용해 작업의 효율성을 높일 수 있다.

다음과 같이 중복, 같은 이름의 데이터가 있는 테이블이 있다고 가정해보자.

 

table 1
(eva,blue) (eva,orange) (luby, pink) (sally, white) (eva,orange) (luby, pink)...

 

앞 테이블의 데이터를 이용한 새로운 테이블을 만들어서 넘버링을 한다.

table 2
1 -> (eva,blue)
2 -> (eva,orange)
3 -> (luby, pink)
4 -> (sally, white)

 

와, 아주 깨끗하다.

(eva,blue) (eva,orange) (luby, pink) (sally, white) (eva,orange) (luby, pink)...
-> 1 2 3 4 2 3...

 

 

▲ 색깔 데이터를 수정할 일이 생겼다

-> table 2에서 한 번 바꾸면 table 1의 해당 데이터가 전부 바뀐다

 

▲ eva라는 동명이인 중 blue 색깔을 가진 사람이 개명을 했다

-> table 2에서 바꾸면 table 1의 해당 사람만 바뀐다 

 

▲ table 1과 table 2이 분리되어 있다 (테이블 분리 실행)

-> 한 번에 보기가 힘들어졌다 (JOIN으로 해결)

 

 

 

테이블 분리

 

list 테이블

-> 중복이 없는 column의 biglist 테이블과, 중복이 있는 column의 tinylist 테이블로 분리할 것이다.

두 테이블의 연결점(joint)은 biglist의 'master_ok' 컬럼 & tinylist의 'id' 컬럼이 될 것이다.

id name master country
1 allen cranberry korea
2 bell cranberry korea
3 chloe blueberry taiwan
4 dani strawberry canada

 

biglist 테이블

CREATE TABLE biglist(
id int(11) not null auto_increment,
name varchar(10) not null,
master_ok int(11) null,     -> 이 부분이 연결점(joint)이다
primary key(id));

 

tinylist 테이블

CREATE TABLE tinylist (
id int(11) not null auto_increment,    -> 이 부분이 연결점(joint)이다
master varchar(10) not null,
country varchar(10) not null,
primary key(id));

 

 

list에서 중복된 column을 tinylist에 정리해보자.

INSERT INTO tinylist
(id, master, country)
VALUES
(1,'cranberry','korea');
INSERT INTO tinylist
(id, master, country)
VALUES
(2,'blueberry','taiwan');
INSERT INTO tinylist
(id, master, country)
VALUES
(3,'strawberry','canada');

 

 

biglist에 데이터를 삽입하며,

연결점이 될 master_ok에는 tinylist에서 맞는 id를 찾아 적어준다.

INSERT INTO biglist
(id,name,master_ok)
VALUES
(1,'allen',1);
INSERT INTO biglist
(id,name,master_ok)
VALUES
(2,'bell',1);
INSERT INTO biglist
(id,name,master_ok)
VALUES
(3,'chole',2);
INSERT INTO biglist
(id,name,master_ok)
VALUES
(4,'dani',3);

 

 

 

완성된 biglist와 tinylist를 출력해보자. (SELECT * FROM {biglist / tinylist})

 

 

biglist 테이블

id name master_ok (joint)
1 allen 1
2 bell 1
3 chloe 2
4 dani 3

 

tinylist 테이블

id (joint) master country
1 cranberry korea
2 blueberry taiwan
3 strawberry canada

 

 

 

 

JOIN

자, 드디어 조인이다.

  SELECT * FROM biglist LEFT JOIN tinylist ON biglist.master_ok = tinylist.id;

 

id name master_ok id master country
1 allen 1 1 cranberry korea
2 bell 1 1 cranberry korea
3 chloe 2 2 blueberry taiwan
4 dani 3 3 strawberry canada

 

 

참조1 - 연결점을 안 보이게 하려면 해당 컬럼(biglist.master_ok와 tinylist.id)을 빼면 된다
 
 SELECT biglist.id,name,biglist.master,country  
 		-> tinylist에도 문자열이 포함된 id와 master는 헷갈리지 않도록 biglist로 지정
 FROM biglist LEFT JOIN tinylist ON biglist.master_ok = tinylist.id;
 
 연결점이 안 보이면 원래의 list와 똑같은 모습이 되지만,
 JOIN을 활용해 효율성 있게 작업할 수 있는 마법이 일어난다.

 

id name master country
1 allen cranberry korea
2 bell cranberry korea
3 chloe blueberry taiwan
4 dani strawberry canada

 

Comments