Database/MySQL

[MySQL 기초] 6. 테이블 분리하고 JOIN하기

  • -
728x90

현재 테이블에는 중복의 문제가 포함되어있다. 데이터가 적을때는 처리하기 쉽겠지만, 데이터가 많아지면 그 처리를 일일이 해주기 힘들어진다. 이를 위해 테이블을 분리해보자.

미리 만들어둔 테이블은 지우기 아까우니 백업해두자.

 

RENAME TABLE topic TO topic\_backup;

 

 

topic 테이블을 아래와 같이 새로 만든다.  

CREATE TABLE `topic` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(30) NOT NULL,
  `description` text,
  `created` datetime NOT NULL,
  `author_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
);

 

author 대신 author_id가 생겼다.  

 

다음으로, author 테이블을 생성하자. 

CREATE TABLE `author` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(20) NOT NULL,
  `profile` varchar(200) DEFAULT NULL,
  PRIMARY KEY (`id`)
);

이렇게 두 테이블이 생성되었고 두 테이블은 비어잇는 상태이다.  

 

각 테이블에 데이터를 입력하자.  

 

--
-- Dumping data for table `author`
--
 
INSERT INTO `author` VALUES (1,'egoing','developer');
INSERT INTO `author` VALUES (2,'duru','database administrator');
INSERT INTO `author` VALUES (3,'taeho','data scientist, developer');

--
-- Dumping data for table `topic`
--
 
INSERT INTO `topic` VALUES (1,'MySQL','MySQL is...','2018-01-01 12:10:11',1);
INSERT INTO `topic` VALUES (2,'Oracle','Oracle is ...','2018-01-03 13:01:10',1);
INSERT INTO `topic` VALUES (3,'SQL Server','SQL Server is ...','2018-01-20 11:01:10',2);
INSERT INTO `topic` VALUES (4,'PostgreSQL','PostgreSQL is ...','2018-01-23 01:03:03',3);
INSERT INTO `topic` VALUES (5,'MongoDB','MongoDB is ...','2018-01-30 12:31:03',1);

 

이제 완성된 두 테이블을 JOIN하여 topic_backup의 모양으로 만들어 보자.  

 

author의 식별자를 기준으로 topic 테이블에 JOIN해주면 다음과 같이 된다.  

SELECT * FROM topic LEFT JOIN author ON topic.author_id = author.id;

topic 테이블의 모든 속성으로 부터 author 테이블을 topic.author_id = author.id 기준으로 JOIN 

 

이 때 author_id 와 id 부분을 제외하기위해 다음과 같이 해보자.

SELECT id, title, discription, created, name, profile 
FROM topic 
LEFT JOIN author 
ON topic.author_id = author.id;

이런 에러가 뜬다. 이유는 id라는 속성(Column)이 애매하다는 뜻이다. 두 테이블 모두 id 값을 가지고 있기 때문이다.  

따라서 속성을 고를때 어떤 테이블의 id인지 확실히 mysql에게 알려주면 된다.  

 

SELECT topic.id, title, description, created, name, profile 
FROM topic 
LEFT JOIN author 
ON topic.author_id = author.id;

id를 좀 더 명확하게 표시하고 싶을때에는 AS를 사용하면 된다.

SELECT topic.id AS topic_id, title, description, created, name, profile 
FROM topic 
LEFT JOIN author 
ON topic.author_id = author.id;

 

728x90
300x250
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.