데이터베이스

SQL5: Select SQL Statement2: Duplication, Set Operation

소재훈 2021. 12. 23. 16:24

데이터베이스 목차

이 글에서는 University Database가 사용된다.

Duplicates

관계형 데이터베이스 모델은 Set기반이기 때문에 중복된 튜플이 없어야 하지만 데이터베이스를 사용하는 실세계에서는 중복이 필요한 경우가 있다. 따라서 SQL에서는 multi-set기반으로 확장시켜 중복을 허용하였다.

관계 대수 6개의 operation을 multi set으로 확장한 것이다.

  • select: σ
  • project: ∏
  • union: ∪
  • set difference: −
  • Cartesian product: ×
  • rename: ρ

r1(A, B)와 r2(C)와 같은 relation이 있다고 하자. 이때 multi set으로 확장된 관계 대수를 적용하면 다음과 같다.

다음과 같은 SQL문은

Select A1, A2, ...,An
from R1, R2, ...,Rm
where P

multi-set으로 확장된 버전의 관계대수로는 다음과 같이 확장될 수 있다.


Set Operation

set operation으로 union, intersect, except를 제공한다. SQL에서의 set연산으로 보면 된다.

union all, intersect all, except all과 같이 set operation 뒤에 all을 붙이게 되면 결과 테이블에 중복을 허용하게 된다.

예를 들어 동일한 튜플이 relation r에서는 m번, s에서는 n번 등장한다면 집합 연산의 결과로 해당튜플은 다음 개수만큼 등장한다.

  • r union all s: m + n
  • r intersect all s: min(m, n)
  • r except all s: max(0, m-n)

Set Operation을 이용한 예시들을 알아보자.

  • 2009년 또는 2010년 가을학기에 강의된 교과목ID(cID)
    (select cID from teaches where semester = ‘Fall’ and year = 2009)
    union
    (select cID from teaches where semester = ‘Fall’ and year = 2010);
  • 2009년과 2010년 가을학기에 강의된 교과목 ID(cID)
    (select cID from teaches where semester = ‘Fall’ and year = 2009)
    intersect
    (select cID from teaches where semester = ‘Fall’ and year = 2010);​
  • 2009년 가을학기에는 강의하였지만 2010년 가을학기에는 강의하지 않은 교과목 ID(cID)
    (select cID from teaches where semester = ‘Fall’ and year = 2009)
    except
    (select cID from teaches where semester = ‘Fall’ and year = 2010);​

중복되는 cID를 모두 출력하고자 한다면 union all, intersect all, except all을 사용하면 된다.