IT 개발노트
join 본문
PK와 FK값의 연관에 의해 JOIN이 성립
- inner join : 조인 조건을 만족하는 행에 대해서만 결과값이 나오는 조인
-> equijoin
-> join ~ on
-> natural join
->
- outter join : 조인 조건을 만족하지 않아도 출력이 가능해야하는 결과를 얻고자 할 때 사용
-> left join
-> ritgt join
-> full join
select * from employee;
select * from department;
-- 1. 데이터 넣기
insert into department values(null, '총무팀');
insert into department values(null, '영업팀');
insert into department values(null, '인사팀');
insert into department values(null, '개발팀');
insert into employee values(null, '현정이', 3);
insert into employee values(null, '경진이', 2);
insert into employee values(null, '둘리', 1);
insert into employee values(null, '진국이', null);
-- inner join
-- 1. 조심 : cartesian products ( M X N ) (100000 X 100000)
select *
from employee, department;
-- 2. equijoin 조인할 개수-1만큼 where절을 걸어줘야한다.
select a.no, a.name, b.name
from employee a, department b
where a.department_no = b.no;
-- 3. join ~ on (ANSI SQL 1999)
select a.no, a.name, b.name
from employee a
join department b
on a.department_no = b.no;
-- outter join
-- 1. left join
select a.no, a.name, ifnull(b.name, '사장님')
from employee a
left join department b
on a.department_no = b.no;
-- 2. right join
select a.no, ifnull(a.name, '채용요망'), b.name
from employee a
right join department b
on a.department_no = b.no;
-- 3. full join
-- mysql/mariadb 지원안함
-- select a.no, ifnull(a.name, '채용요망'), b.name
-- from employee a
-- full join department b
-- on a.department_no = b.no;
-- 1) 현재 회사 상황을 반영한 직원별 근무부서를 사번, 직원 전체이름, 근무부서 형태로 출력해 보세요.
select a.emp_no as '사번',
concat(a.first_name, ' ', a.last_name) as '전체이름',
c.dept_name as '근무부서'
from employees a, dept_emp b, departments c
where a.emp_no = b.emp_no
and b.dept_no = c.dept_no
and b.to_date = '9999-01-01';
-- 2) 현재 회사에서 지급되고 있는 급여체계를 반영한 결과를 출력하세요.
-- 사번, 전체이름, 연봉 이런 형태로 출력하세요.
select a.emp_no as '사번',
concat(a.first_name, ' ', a.last_name) as '전체이름',
b.salary as '연봉'
from employees a, salaries b
where a.emp_no = b.emp_no
and b.to_date = '9999-01-01'
order by b.salary desc;
-- ANSI JOIN 1999
-- 1. join ~ on
select a.emp_no, a.first_name as '직원명', c.dept_name as '부서명'
from employees a
join dept_emp b
on a.emp_no = b.emp_no
join departments c
on b.dept_no = c.dept_no;
select a.first_name, b.title
from employees a
join titles b
on a.emp_no = b.emp_no;
-- 2. natural join
select a.first_name, b.title
from employees a
natural join titles b;
-- 2-1 natural join의 문제점
select count(*)
from salaries a
natural join titles b;
-- 2-2 join ~ using => natural join의 문제점 해결
select count(*)
from salaries a
join titles b using(emp_no);