[오라클] join

심심이·2024년 3월 27일
0

oracle

목록 보기
40/40

조인 = 테이블 + 테이블
테이블 A와 B가 있다고 했을 때 A+B를 같이 보고 싶을 때 join을 사용한다.

  • cross join: 카타시안 곱, 모든 경우의 수를 join하여 보여준다
  • inner join: 테이블 a와 b에 교집합을 말한다.
  • outer 조인 :
  1. LEFT OUTER JOIN: 왼쪽 테이블의 모든 값 출력
    2.RIGHT OUTER JOIN: 오른쪽 테이블의 모든 값 출력
    3.FULL OUTER 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을 해야 한다.

non-equi 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 연봉;

SELF JOIN

자기 자신 테이블을 자기자신의 테이블과 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;
profile
개발하는 심심이

0개의 댓글