제2절_집합_연산자(SET_OPERATOR)

조회 수 5029 추천 수 0 2012.03.18 22:27:13
ljw *.232.65.107

제2절 집합 연산자(SET OPERATOR)



집한 연산자

  1. 두개 이상의 연관된 테이블에서 데이터를 조회하는 방법
  2. 여러개의 질의의 결과를 연결하여 하나로 결합
  3. 튜닝관점에서 실행계획을 분리하고자 할때

SQL_204.jpg
SQL_205.jpg

--UNION 
SELECT DEPARTMENT_ID, EMPLOYEE_ID, FIRST_NAME, LAST_NAME
  FROM EMPLOYEES
WHERE DEPARTMENT_ID=10
UNION
SELECT DEPARTMENT_ID, EMPLOYEE_ID, FIRST_NAME, LAST_NAME
  FROM EMPLOYEES
WHERE DEPARTMENT_ID=20
ORDER BY LAST_NAME;

이미지 17.png

--같은 컬럼에 대한 IN연산자 대체 UNION 효과
SELECT DEPARTMENT_ID, EMPLOYEE_ID, FIRST_NAME, LAST_NAME
  FROM EMPLOYEES
WHERE DEPARTMENT_ID IN (10, 20);
이미지 19.png


UNION ALL
UNION ALL은 UNION과 다르게 집합내에서 중복이 생길수 있음(단순 결합)
--UNION ALL
SELECT DEPARTMENT_ID, EMPLOYEE_ID, FIRST_NAME, LAST_NAME
  FROM EMPLOYEES
WHERE DEPARTMENT_ID IN (10, 20)
UNION ALL
SELECT DEPARTMENT_ID, EMPLOYEE_ID, FIRST_NAME, LAST_NAME
  FROM EMPLOYEES
WHERE DEPARTMENT_ID IN (10, 20)
ORDER BY LAST_NAME;
이미지 20.png


--MINUS
SELECT DEPARTMENT_ID, EMPLOYEE_ID, FIRST_NAME, LAST_NAME
  FROM EMPLOYEES
WHERE DEPARTMENT_ID IN (10, 20)
MINUS
SELECT DEPARTMENT_ID, EMPLOYEE_ID, FIRST_NAME, LAST_NAME
  FROM EMPLOYEES
WHERE DEPARTMENT_ID =10
ORDER BY LAST_NAME;
이미지 21.png

--NOT IN를 이용한 MINUS효과
SELECT DEPARTMENT_ID, EMPLOYEE_ID, FIRST_NAME, LAST_NAME
  FROM EMPLOYEES A
WHERE DEPARTMENT_ID IN (10, 20)
 AND EMPLOYEE_ID NOT IN 
              (SELECT EMPLOYEE_ID
                 FROM EMPLOYEES
                WHERE DEPARTMENT_ID = 10);
이미지 22.png


--NOT IN를 이용한 MINUS효과
SELECT DEPARTMENT_ID, EMPLOYEE_ID, FIRST_NAME, LAST_NAME
  FROM EMPLOYEES A
WHERE DEPARTMENT_ID IN (10, 20)
INTERSECT
 SELECT DEPARTMENT_ID, EMPLOYEE_ID, FIRST_NAME, LAST_NAME
  FROM EMPLOYEES A
WHERE DEPARTMENT_ID = 10;
이미지 24.png


--IN연산자를 이용한 INTERSECT효과
SELECT DEPARTMENT_ID, EMPLOYEE_ID, FIRST_NAME, LAST_NAME
  FROM EMPLOYEES A
WHERE DEPARTMENT_ID IN (10, 20)
  AND EMPLOYEE_ID IN 
               (SELECT EMPLOYEE_ID
                FROM EMPLOYEES 
              WHERE DEPARTMENT_ID = 10);
이미지 25.png