--
-- 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;