본문 바로가기
DataBase/Oracle

JOIN/EQUI-JOIN) CROSS JOIN

by 박채니 2022. 4. 19.

안녕하세요, 코린이의 코딩 학습기 채니 입니다.

 

개인 포스팅용으로 내용에 오류 및 잘못된 정보가 있을 수 있습니다.


CROSS JOIN

- 상호 조인

- 모든 경우의 수대로 조인 처리

- 기준 조건절이 없음

 

select
    *
from
    employee e cross join department d;

총 216행이 인출된 것을 확인할 수 있으며, 이는 employee의 모든 행이 department의 모든 행과 경우의 수대로 조인 처리 되었기 때문입니다.

따라서 employee의 모든 행이 D1~D9까지 조인 처리 되었기 때문에

employee 테이블의 행 수 (24) * department 테이블의 행 수 (9) = 216행이 추출되었습니다.

 

[오라클 전용문법 버전]

- where 조인 조건을 생략

select
    *
from
    employee e, department d;

 

응용) 사원 별 평균 월급과의 차이 조회

select
    emp_name,
    salary - avg(salary)
from
    employee;

나의 월급 - 평균 월급이기 때문에 위처럼 해도 될 것 같지만 

"ORA-00937: not a single-group group function" 오류가 발생하게 됩니다.

그룹 함수와 일반 컬럼이 같이 올 수 없기 때문입니다. 이런 경우 cross join을 사용할 수 있습니다.

 

select
    emp_name 사원명,
    salary - avg_sal 월급차이
from
    employee e cross join (select trunc(avg(salary)) avg_sal from employee) s;

 

직급 별 평균 급여와 사원의 급여 차이

-- 1. 직급 별 평균 급여
select
    job_code,
    trunc(avg(salary)) avg_sal
from
    employee
group by
    job_code
order by
    1;
    
-- 2. join 시 제외되는 행 찾기
-- employee에 기준 컬럼 job_code가 null인 사원 조회 : 없음
select count(*) from employee where job_code is null;
-- employee에 매칭 되는 행이 없는 행 : 없음

-- 3. employee 직급 별 평균 급여 join
select
    e.emp_name 사원명,
    e.salary 급여,
    e.job_code 직급코드,
    a.avg_sal 평균급여,
    e.salary - a.avg_sal 급여차이
from
    employee e inner join (
        select
            job_code,
            trunc(avg(salary)) avg_sal
        from
            employee
        group by
            job_code
        order by
            1
        ) a
        on e.job_code = a.job_code;