다중 조인

SQL에서 데이터 조인하기

Maham Faisal Khan

Senior Content Developer, DataCamp

조인에 조인 더하기

SELECT *
FROM left_table
INNER JOIN right_table
ON left_table.id = right_table.id

INNER JOIN another_table ON left_table.id = another_table.id;

참고. 사용 사례에 따라 left_table 또는 right_tableON 절에 사용할 수 있음.

SQL에서 데이터 조인하기

조인에 조인 더하기

세계 지도자 데이터베이스의 prime_minister_terms 테이블

The prime_minister_terms table, showing two columns: the name of the prime_minister and the year they assumed office.

SQL에서 데이터 조인하기

어떤 것부터 조인할까요?

SELECT p1.country, p1.continent, 
       president, prime_minister
FROM prime_ministers as p1
INNER JOIN presidents as p2
USING(country);
| country  | continent     | president               | prime_minister   |
| -------- | ------------- | ----------------------- | ---------------- |
| Egypt    | Africa        | Abdel Fattah el-Sisi    | Mostafa Madbouly |
| Portugal | Europe        | Marcelo Rebelo de Sousa | Luís Montenegro  |
| Pakistan | Asia          | Asif Ali Zardari        | Shehbaz Sharif   |
| India    | Asia          | Droupadi Murmu          | Narendra Modi    |
SQL에서 데이터 조인하기

조인 체이닝

A diagram showing the result set of the merge from the previous slide (presidents and prime_ministers) with a new table, prime_minister_terms. The result consists of five columns: country, continent, president, prime_minister, and pm_start.

SQL에서 데이터 조인하기

조인 체이닝

-- SQL query for chaining inner joins
SELECT 
    p1.country, 
    p1.continent, 
    president, 
    prime_minister, 
    pm_start
FROM prime_ministers as p1
INNER JOIN presidents as p2
USING(country)

INNER JOIN prime_minister_terms as p3 USING(prime_minister);
SQL에서 데이터 조인하기

무엇을 ON으로 조인할까요?

SELECT * 
FROM left_table
INNER JOIN right_table
ON left_table.id = right_table.id;
INNER JOIN 필드에 ON을 사용하는 id 다이어그램

A diagram showing that when matching on one column, sometimes the joining field from left table finds multiple matches in the joining field from right table. The result set has multiple records for each id in the right table that matched with the left table.

SQL에서 데이터 조인하기

다중 키로 조인하기

SELECT * 
FROM left_table
INNER JOIN right_table
ON left_table.id = right_table.id
    AND left_table.date = right_table.date;
id AND date 필드를 ON으로 연결하는 INNER JOIN 다이어그램

A diagram showing that the number of records returned in the result set can be reduced if multiple joining fields are used. Here, both id and date are used to join the two tables.

SQL에서 데이터 조인하기

연습해봅시다!

SQL에서 데이터 조인하기

Preparing Video For Download...