조인 = 테이블 + 테이블
테이블 A와 B가 있다고 했을 때 A+B를 같이 보고 싶을 때 join을 사용한다.
JOIN을 할 때는 꼭 ON절에서 테이블끼리 이어주는 행이 있어야 한다.
간단한 예시는 아래와 같다.
WITH E as
(
select employee_id,
first_name || ' ' || last_name AS FULLNAME,
salary,
department_id
from employees
where department_id in(30,60)
)
,
D as
(
select department_id, department_name
from departments
where department_id in(30,60)
)
select E.department_id AS 부서번호
, department_name AS 부서명
, employee_id AS 사원번호
, fullname AS 사원명
, salary AS 기본급여
from E JOIN D
on E.department_id = D.department_id;
inner 조인의 경우 null값이 나오지 않으므로, null인 행이 나오게 하려면 outer join을 해야 한다.
조인 조건절에 사용되는 칼럼의 값이 특정한 범위에 속할 때는 between A and B 를 사용할 수 있다.
예시 코드는 다음과 같다.
select employee_id as 사원번호,
first_name || ' ' || last_name as 사원명,
to_char(nvl(salary + (salary * commission_pct), salary) * 12, '999,999') as 연봉,
taxpercent as 세율,
to_char(trunc( (nvl(salary + (salary * commission_pct), salary) * 12) * taxpercent ), '99,999') as 소득세액 --연봉 x 세율
from employees E JOIN tbl_taxindex T
ON nvl(salary + (salary * commission_pct), salary) * 12 BETWEEN T.lowerincome AND T. highincome -- 조인 조건절
order by 연봉;
자기 자신 테이블을 자기자신의 테이블과 join, 즉 말그대로 self join을 뜻한다.
--- SELF JOIN(자기조인)을 사용하여 tbl_authorbook 테이블에서 공저(도서명은 동일하지만 작가명이 다른 도서)로 지어진 도서정보를 나타내세요... ---
---
/*
---------------------------------
도서명 작가명 로얄티
---------------------------------
로빈슨크루소 한석규 800
로빈슨크루소 이순신 500
그리스로마신화 유관순 1200
그리스로마신화 이혜리 1300
그리스로마신화 서강준 1700
---------------------------------
*/
select * from tbl_authorbook;
select distinct
B.bookname,
B.authorname,
B.loyalty
from tbl_authorbook A join tbl_authorbook B
ON A.bookname = B.bookname and A.authorname != B.authorname
order by 1 desc;