SQL 기초 - 10) 이젠 테이블이 2개입니다

이희수·2024년 12월 17일

다음과 같은 직원(employees) 테이블과 부서(departments) 테이블이 있습니다.

  • employees 테이블
iddepartment_idname
1101르탄이
2102배캠이
3103구구이
4101이션이
  • departments 테이블
idname
101인사팀
102마케팅팀
103기술팀
  1. 현재 존재하고 있는 총 부서의 수를 구하는 쿼리를 작성해주세요!

SELECT DISTINCT COUNT(*) AS 부서의_수
FROM departments;

중복되는 부서없이 count할 수 있도록 distinct 키워드를 써준다

  1. 모든 직원과 그들이 속한 부서의 이름을 나열하는 쿼리를 작성해주세요!

SELECT employees.name AS employee_name, departments.name AS department_name
FROM employees
JOIN departments ON employees.department_id = departments.id;

직원 정보와 부서 이름이 각각 employees테이블과 departments테이블에 있으므로, 두 테이블을 join으로 결합시킨 뒤 결합된 테이블에서 원하는 정보를 select하는 방식으로 쿼리를 작성한다.

  1. '기술팀' 부서에 속한 직원들의 이름을 나열하는 쿼리를 작성해주세요!

SELECT employees.name
FROM employees
JOIN departments ON employees.department_id = departments.id
WHERE departments.name = '기술팀';

원하는 정보가 두 테이블에 분산되어 있으므로, 우선 join해준 뒤, 원하는 조건을 where절에 써준다

  1. 부서별로 직원 수를 계산하는 쿼리를 작성해주세요!

SELECT departments.name, COUNT(*) AS 부서별직원
FROM employees
JOIN departments on employees.department_id = departments.id
GROUP BY departments.name;

부서를 기준으로 부서의 직원수를 count해주는 것이니, 부서로 그룹핑 해준다.

  1. 직원이 없는 부서의 이름을 찾는 쿼리를 작성해주세요!

select departments.name
from employees
right join departments
on employees.department_id = departments.id
where employees.id = null

직원 데이터가 없는 부서이더라도 join한 테이블에 정보를 보여주기 위해, departments테이블의 모든 정보를 살리며 join할 수 있도록 right join을 써준다.
From departments LEFT JOIN employees
위와 같이 작성해도 마찬가지로 employees정보가 없는 department정보도 살리며 join할 수 있다.
join한 테이블에서 직원 정보가 없는 부서를 찾기 위해 where절에 조건을 써준다

  1. '마케팅팀' 부서에만 속한 직원들의 이름을 나열하는 쿼리를 작성해주세요!

SELECT e.name
FROM employees e JOIN departments d ON e.department_id = d.id
WHERE d.name = '마케팅팀';

where절에 원하는 조건을 작성해준다

0개의 댓글