IA/DB

[mysql] JOIN : Left

kiostory 2019. 1. 1. 17:56






 MySQL  kio.comwlqw18xbq.ap-northeast-2.rds.amazonaws.com:3306 ssl  kio  SQL > select * from author;
+----+--------+---------------------------+
| id | name   | profile                   |
+----+--------+---------------------------+
|  1 | egoing | developer                 |
|  2 | duru   | database administrator    |
|  3 | taeho  | data scientist, developer |
+----+--------+---------------------------+
3 rows in set (0.0056 sec)


 MySQL  kio.comwlqw18xbq.ap-northeast-2.rds.amazonaws.com:3306 ssl  kio  SQL > select * from topic;
+----+------------+-------------------+---------------------+-----------+
| id | title      | description       | created             | author_id |
+----+------------+-------------------+---------------------+-----------+
|  1 | MySQL      | MySQL is...       | 2018-01-01 12:10:11 |         1 |
|  2 | Oracle     | Oracle is ...     | 2018-01-03 13:01:10 |         1 |
|  3 | SQL Server | SQL Server is ... | 2018-01-20 11:01:10 |         2 |
|  4 | PostgreSQL | PostgreSQL is ... | 2018-01-23 01:03:03 |         3 |
|  5 | MongoDB    | MongoDB is ...    | 2018-01-30 12:31:03 |         1 |
+----+------------+-------------------+---------------------+-----------+
5 rows in set (0.0056 sec)


 MySQL  kio.comwlqw18xbq.ap-northeast-2.rds.amazonaws.com:3306 ssl  kio  SQL > select * from topic left join author on topic.author_id=author.id;
+----+------------+-------------------+---------------------+-----------+----+--------+---------------------------+
| id | title      | description       | created             | author_id | id | name   | profile                   |
+----+------------+-------------------+---------------------+-----------+----+--------+---------------------------+
|  1 | MySQL      | MySQL is...       | 2018-01-01 12:10:11 |         1 |  1 | egoing | developer                 |
|  2 | Oracle     | Oracle is ...     | 2018-01-03 13:01:10 |         1 |  1 | egoing | developer                 |
|  5 | MongoDB    | MongoDB is ...    | 2018-01-30 12:31:03 |         1 |  1 | egoing | developer                 |
|  3 | SQL Server | SQL Server is ... | 2018-01-20 11:01:10 |         2 |  2 | duru   | database administrator    |
|  4 | PostgreSQL | PostgreSQL is ... | 2018-01-23 01:03:03 |         3 |  3 | taeho  | data scientist, developer |
+----+------------+-------------------+---------------------+-----------+----+--------+---------------------------+
5 rows in set (0.0058 sec)


Left Join 과 Right Join의 차이점

쿼리를 작성하면 SQL 표준은 사용자가 첫 번째 테이블을 왼쪽에 두 번째 테이블을 오른쪽에 있는 것으로 간주.

그래서 첫 번째 테이블의 모든 행과 두 번째 테이블이 일치하는 행이 있으면 Left Join을 사용하고,

반대로 두 번째 테이블의 모든 행과 첫 번째 테이블의 일치하는 행을 알고 싶으면 Right Join을 사용.