Notice
Recent Posts
Recent Comments
Link
«   2026/03   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31
Archives
Today
Total
관리 메뉴

코딩기록

Day - 35 [Maria DB] SET(집합) 본문

study

Day - 35 [Maria DB] SET(집합)

9-99zy 2023. 3. 22. 16:30

SET(집합)

  • 우리는 두 개의 테이블을 집합연산 할 수 있다.
  • UNION 은 중복 확인을 위해 전체 검색 후 정렬하여 검사를 수행 하기 때문에 성능에 좋지 않다.


 

SET 개념
  • 다수의 테이블을 이용하여 집합 연산을 수행 할 수 있다.
  • 합집합(UNION, UNION ALL), 교집합(INTERSECT), 차집합(NOT IN) 이 존재한다.
  • UNION 중복 제거 시 시간이 오래 걸려 성능저하가 발생한다.
  • [TABLE|QRY] [UNION|UNION ALL|INTERSECT] [TABLE|QRY2]
  •  
1. UNION(중복을 제거한 합집합)
-- [TABLE|QRY] [UNION|UNION ALL|INTERSECT] [TABLE|QRY2]

1. UNION(중복을 제거한 합집합)
-- 동일한 칼럼이 한 개 이상은 있어야 한다.
select deptno from emp
union
select deptno from dept order by deptno;

union 결과

-- union 을 통해서 full outer join 효과를 줄 수 있다.
-- full outer join : 양쪽 데이터에 각각 더 있는 값을 보여줌 
-- 더 있는 값이란 양 쪽 테이블 다 매칭되지 않고 남은 데이터를 보여준다는 의미이다.
select e.deptno, e.ename , d.deptname from emp e left outer join dept d on e.deptno = d.deptno
union
select d.deptno, e.ename , d.deptname from emp e right outer join dept d on e.deptno = d.deptno;

 

 

2. UNION ALL (중복을 제거하지 않은 합집합)
select deptno from emp
union all
select deptno from dept order by deptno;

union all 결과 값

 

3. INTERSECT(교집합)

두 쿼리 사이에 중복된 내용만 가져온다.

select deptno from emp
intersect
select deptno from dept order by deptno;

intersect 교집합 결과

4. MINUS (NOT IN)
select distinct deptno from emp; -- 1,2,4,6
select deptno from dept; -- 1,2,3,4,5

-- emp - dept
select deptno from emp where deptno not in(select deptno from dept); -- 6

-- dept - emp
select deptno from dept where deptno not in(select deptno from emp); -- 3,5

 

-- emp 와 dept 를 합집합 한 내용을 emp 와 교집합

(select deptno from emp union all select deptno from dept) 
intersect
select deptno from emp; -- 1,2,4,6

 

-- UNION 대신 뭘 쓰지? 하고, 하고 , 하면 느려질 수 밖에 없음 union all 사용

-- distinct : 중복 제거

select distinct u.deptno
(select deptno from emp
	union all
select deptno from dept order by deptno) u;