SQL 5-9 세개 이상의 테이블 조인
관련링크
본문
5-10 세 개 이상의 테이블 조인
․ n개의 테이블을 조인하려면 최소 n-l개의 조인 조건이 필요하다.
․ 세 개의 테이블을 조인하려면 최소 두 개의 조인 조건이 필요하다.
예제) 오라클 디비 예제 : SELECT e.last_name, d.department_name, 1.city
FROM employees e, departments d, locations 1
WHERE e.department_id = d.department_id
AND d.location_id = 1.location_id;
☞설명)
세 개이상의 테이블을 조인할 경우가 있다.
각 사원의 이름,부서 및 도시를 표시하려면 EMPLOYEES,DEPARTMENTS 및 LOCATIONS테이블을 조인해야 한다.
MSSQL 디비 예제 :
select t.title_id, t.title, s.stor_id, s.qty, s.title_id , p.pub_id, p.logo, p.pr_info
from titles t, sales s , pub_info p
where t.title_id = s.title_id AND t.pub_id = p.pub_id
① ON절로 3-way조인 작성
3-Way 조인은 세 테이블 조인이다.
SQL : 1999표준 구문에서, 조인은 왼쪽에서 오른쪽으로 수행되므로 수행될 첫 번째 조인은 EMPLOYEES JOIN
DEPARTMENTS이다.
예제)
오라클 디비 예제 : SELECT employee_id, city, department_name
FROM employees e JOIN departments d
ON d.department_id = e.department_id JOIN locations l
ON d.location id = l.location id;
☞설명)
첫 번째 조인 조건은 EMPLOYEES 및 DEPARTMENTS의 열을 참조할 수 있지만 LOCATIONS의 열은 참조할 수 없다.
두 번째 조인 조건은 세 테이블 모두의 열을 참조할 수 있다.
이 예제는 다음과 같이 3-way등가 조인으로도 작성할 수 있습니다.
SELECT employee_id, city, department_name
FROM employees, departments, locations
WHERE employees.department_id = departments.department_id
AND departments.location_id = locations.location_id;