-- JOIN
두개 이상의 테이블을 연결해 데이터를 검색하는 방법이다.
보통 둘이상의 행(ROW)들의 공통된 값 Primary key, Foreign key 값을
사용해서 join을 한다,
두개 이상의 테이블을 select 문장 안에서 조인 하려면 적어도 하나의 컴럼이
두 테이블에서 공유 되어 있어야 한다.
inner Join *****
cross Join *
outer Join
left outer ***
right outer ***
self Join *****
SQL : Orcle, Ansi Sql
-- inner Join --
-- 겹치는 부분만 조인
-- Ansi SQL
SELECT EMPLOYEE_ID,FIRST_NAME,SALARY,
E.DEPARTMENT_ID, D.DEPARTMENT_ID,DEPARTMENT_NAME
FROM EMPLOYEES E INNER JOIN DEPARTMENTS D
ON E.DEPARTMENT_ID = D.DEPARTMENT_ID;
-- Oracle SQL
SELECT EMPLOYEE_ID,LAST_NAME,SALARY,
E.DEPARTMENT_ID, D.DEPARTMENT_ID,DEPARTMENT_NAME
FROM EMPLOYEES E, DEPARTMENTS D
WHERE E.DEPARTMENT_ID = D.DEPARTMENT_ID
AND LAST_NAME = 'King';
-- CORSS JOIN --
-- 경우의수 마다 다 보여지게? // 사용빈도 적음
-- ANSI SQL
SELECT E.EMPLOYEE_ID, E.FIRST_NAME, E.DEPARTMENT_ID,
D.DEPARTMENT_ID, D.DEPARTMENT_NAME, D.LOCATION_ID
FROM EMPLOYEES E CROSS JOIN DEPARTMENTS D;
-- Oracle SQL
SELECT E.EMPLOYEE_ID, E.FIRST_NAME, E.DEPARTMENT_ID,
D.DEPARTMENT_ID, D.DEPARTMENT_NAME, D.LOCATION_ID
FROM EMPLOYEES E , DEPARTMENTS D
ORDER BY E.DEPARTMENT_ID;
-- OUTER JOIN --
-- LEFT JOIN
-- ANSI
SELECT E.EMPLOYEE_ID, E.LAST_NAME,
E.DEPARTMENT_ID, D.DEPARTMENT_ID,
D.DEPARTMENT_NAME
FROM EMPLOYEES E LEFT OUTER JOIN DEPARTMENTS D
ON E.DEPARTMENT_ID = D.DEPARTMENT_ID;
-- ORACLE
SELECT E.EMPLOYEE_ID, E.LAST_NAME,
E.DEPARTMENT_ID, D.DEPARTMENT_ID,
D.DEPARTMENT_NAME
FROM EMPLOYEES E , DEPARTMENTS D
WHERE E.DEPARTMENT_ID = D.DEPARTMENT_ID(+);
-- RIGHT JOIN
-- ANSI
SELECT E.EMPLOYEE_ID, E.LAST_NAME,
E.DEPARTMENT_ID, D.DEPARTMENT_ID,
D.DEPARTMENT_NAME
FROM EMPLOYEES E RIGHT OUTER JOIN DEPARTMENTS D
ON E.DEPARTMENT_ID = D.DEPARTMENT_ID;
-- ORACLE
SELECT E.EMPLOYEE_ID, E.LAST_NAME,
E.DEPARTMENT_ID, D.DEPARTMENT_ID,
D.DEPARTMENT_NAME
FROM EMPLOYEES E , DEPARTMENTS D
WHERE E.DEPARTMENT_ID(+) = D.DEPARTMENT_ID;
-- 차집합
SELECT E.EMPLOYEE_ID, E.LAST_NAME,
E.DEPARTMENT_ID, D.DEPARTMENT_ID,
D.DEPARTMENT_NAME
FROM EMPLOYEES E , DEPARTMENTS D
WHERE E.DEPARTMENT_ID = D.DEPARTMENT_ID(+)
AND E.DEPARTMENT_ID IS NULL;
-- SELF JOIN --> 동일한 테이블을 조인 시키다
SELECT A.EMPLOYEE_ID , A.LAST_NAME "사원",
A.MANAGER_ID "사원의 상사 ID",
B.EMPLOYEE_ID, B.LAST_NAME "상사"
FROM EMPLOYEES A, EMPLOYEES B
WHERE A.MANAGER_ID = B.EMPLOYEE_ID;
-- A : 사원 B : 매니저
-- 계층형 구조
SELECT A.EMPLOYEE_ID , A.FIRST_NAME,
A.MANAGER_ID,
B.EMPLOYEE_ID, B.FIRST_NAME "매니저이름"
FROM EMPLOYEES A, EMPLOYEES B
WHERE A.MANAGER_ID = B.EMPLOYEE_ID(+)
CONNECT BY PRIOR A.MANAGER_ID = A.EMPLOYEE_ID; -- 상향식
SELECT A.EMPLOYEE_ID , A.FIRST_NAME,
A.MANAGER_ID,
B.EMPLOYEE_ID, B.FIRST_NAME "매니저이름"
FROM EMPLOYEES A, EMPLOYEES B
WHERE A.MANAGER_ID = B.EMPLOYEE_ID(+)
CONNECT BY A.MANAGER_ID = PRIOR A.EMPLOYEE_ID; -- 하향식
'Oracle Database > SQL' 카테고리의 다른 글
SQL 특수Query (0) | 2018.06.26 |
---|---|
SQL SUB QUERY (0) | 2018.06.26 |
SQL 쿼리문 기본 (0) | 2018.06.26 |
SQL 쿼리 그룹 (0) | 2018.06.26 |
SQL 쿼리 정렬 (0) | 2018.06.26 |