SQL

SET Operator(SET 연산자, 집합연산자) - INTERSECT (교집합), MINUS (차집합)

에어팟맥스 2022. 7. 11. 17:44

각 테이블마다 동일한 행 추가

  insert into tbl_panmae_202205(panmaedate, jepumname, panmaesu)
  values( to_date('2021-04-05', 'yyyy-mm-dd'), '쵸코파이', 10);
  
  insert into tbl_panmae_202206(panmaedate, jepumname, panmaesu)
  values( to_date('2021-04-05', 'yyyy-mm-dd'), '쵸코파이', 10);
  
  insert into tbl_panmae(panmaedate, jepumname, panmaesu)
  values( to_date('2021-04-05', 'yyyy-mm-dd'), '쵸코파이', 10);
  
  commit;

동일한 행 조회

    select *
    from tbl_panmae_202205
    INTERSECT
    select *
    from tbl_panmae_202206
    INTERSECT
    select *
    from tbl_panmae;
    -- 21/04/05	쵸코파이	10

삭제

    delete from tbl_panmae_202205 
    where jepumname = '쵸코파이';
    
    delete from tbl_panmae_202206 
    where jepumname = '쵸코파이';
    
    delete from tbl_panmae
    where jepumname = '쵸코파이';
    
    commit;

 

 

 

 


------- ===== **** MINUS (차집합) **** ===== -------

 

백업테이블 조회

    select *
    from TBL_EMPLOYEES_BACKUP;

사원번호가 173,185,195인 사원 조회

    select *
    from employees
    where employee_id in(173,185,195);

백업테이블의 사원번호가 173,185,195인 사원 삭제

    delete from employees 
    where employee_id in(173,185,195);
    -- 3개 행 이(가) 삭제되었습니다.

 

개발자가 실수로 employees 테이블에 있던 사원들을 삭제(delete)한 경우,
        그런데 누구를 삭제했는지 모름.
        이때 백업된 TBL_EMPLOYEES_BACKUP 테이블을 이용하여 삭제된 사원들을 복구할 수 있다.

 

 

 -- TBL_EMPLOYEES_BACKUP 테이블에만 존재하고 employees 테이블에는 존재하지 않는 행들을 찾아주는 것

    select *
    from TBL_EMPLOYEES_BACKUP
    MINUS
    select *
    from employees;

 

    insert into employees
    select *
    from TBL_EMPLOYEES_BACKUP
    MINUS
    select *
    from employees;
    -- 3개 행 이(가) 삽입되었습니다.
    
    commit;
    
    
    select *
    from employees
    where employee_id in(173,185,195);
    -- 복구 완료