SQL Server / Query / JOIN
JOIN으로 여러 개의 테이블의 데이터를 연결하여 조회할 수 있다.
다음과 같은 두 개의 테이블이 있다고 하자. country에는 나라의 이름이, city에는 도시의 이름이 있다.
목차
INNER JOIN
- country 테이블의 country_no와 city 테이블의 country_no가 같은 것을 연결한다.
- 두 테이블에 모두 존재하는 데이터를 출력한다.
select country.country_name, city.city_name from country inner join city on country.country_no = city.country_no ;
LEFT JOIN
- country 테이블의 country_no와 city 테이블의 country_no가 같은 것을 연결한다.
- country 테이블에 있는 데이터는 모두 출력하고, city 테이블에 연결된 값이 있으면 그 값을 출력한다.
select country.country_name, city.city_name from country left join city on country.country_no = city.country_no ;
RIGHT JOIN
- country 테이블의 country_no와 city 테이블의 country_no가 같은 것을 연결한다.
- city 테이블에 있는 데이터는 모두 출력하고, country 테이블에 연결된 값이 있으면 그 값을 출력한다.
select country.country_name, city.city_name from country right join city on country.country_no = city.country_no ;
- 다음과 결과는 같다.
select country.country_name, city.city_name from city left join country on country.country_no = city.country_no ;
FULL JOIN
- country 테이블의 country_no와 city 테이블의 country_no가 같은 것을 연결한다.
- 두 테이블의 모든 데이터를 출력하는데, 연결된 것이 있다면 같은 행에 출력한다.
select country.country_name, city.city_name from country full join city on country.country_no = city.country_no ;
CROSS JOIN
- country 테이블의 값 하나하나에 city 테이블의 모든 값을 출력한다.
select country.country_name, city.city_name from country cross join city ;