JOIN을 사용하면 서로 다른 테이블에 저장된 데이터를 조합하여 필요한 정보를 하나의 결과로 얻을 수 있다.
NATURAL JOIN과 Cartesian Product는 여러개의 테이블들을 JOIN하여 결과를 얻어내는 방식들 중 하나이다.
NATURAL JOIN
두 테이블 간에 동일한 이름을 가진 열을 기준으로 조인하는 방식
NATURAL JOIN은 특별한 조인 조건이 필요하지 않으며, 동일한 이름을 가진 모든 열을 기준으로 조인한다.
동일한 이름의 모든 열에 대해 Join하기 때문에 의도치 않은 결과가 나올 수 있다. 이 때에는 Natural Join보다 JOIN ON을 통해 조건을 명시적으로 지정하는 것이 좋다.
Cartesian Product (카티시안 곱)
두 테이블 간의 모든 가능한 조합을 반환하는 방식이다.
어떤 조인 조건도 사용하지 않고, 두 테이블의 모든 행과 열을 조합하여 결과를 생성한다.
결과는 두 테이블의 행 수를 곱한 만큼의 행을 가지게 된다. (만약 A와 B 테이블의 행이 10개씩 있다면 카티시안 곱의 결과는 100행)
행이 모든 경우의 수가 들어가 필요없는 행까지 포함되므로, 조건절을 지정하여 사용할 수 있다.
일반적으로는 카티시안 곱 보다는 Join문들을 많이 사용한다.
고객의 이름과 고객이 주문한 도서의 이름을 구하시오.
# Natural join
select name, bookname from customer
natural join orders natural join book;
# Cartesian product
select name, bookname from customer c, orders o, book b
where c.custid = o.custid and b.bookid = o.bookid;
가격이 20,000원인 도서를 주문한 고객의 이름과 도서의 이름을 구하시오.
# Natural join
select c.name, b.bookname from customer c
natural join orders o natural join book b where b.price = 20000;
# Cartesian product
select c.name, b.bookname from customer c, orders o, book b
where c.custid = o.custid and b.bookid = o.bookid and b.price = 20000;
“박지성” 고객이 구입한 모든 도서의 도서명, 출판사, 가격을 구하시오.
# Natural join
select b.bookname, b.publisher, b.price from customer c
natural join orders o natural join book b where c.name = '박지성';
# Cartesian product
select b.bookname, b.publisher, b.price from customer c, orders o, book b
where c.custid = o.custid and b.bookid = o.bookid and c.name = '박지성';
“박지성” 또는 “장미란” 고객이 구입한 모든 도서의 도서명, 출판사, 가격을 구하시오.
# Natural join
select b.bookname, b.publisher, b.price from customer c
natural join orders o natural join book b where c.name = '박지성' or c.name = '장미란';
# Cartesian product
select b.bookname, b.publisher, b.price from customer c, orders o, book b
where c.custid = o.custid and b.bookid = o.bookid
and (c.name = '박지성' or c.name = '장미란');