Collect payroll records for each department
Dept_no dept_name dept_name and sum are given
CREATE TABLE `departments` (
`dept_no` char(4) NOT NULL,
`dept_name` varchar(40) NOT NULL,
PRIMARY KEY (`dept_no`));
CREATE TABLE `dept_emp` (
`emp_no` int(11) NOT NULL,
`dept_no` char(4) NOT NULL,
`from_date` date NOT NULL,
`to_date` date NOT NULL,
PRIMARY KEY (`emp_no`,`dept_no`));
CREATE TABLE `salaries` (
`emp_no` int(11) NOT NULL,
`salary` int(11) NOT NULL,
`from_date` date NOT NULL,
`to_date` date NOT NULL,
PRIMARY KEY (`emp_no`,`from_date`));
Copy the code
My submission is
select d.dept_no, d.dept_name, count(s.salary) as sum
from departments as d
left join dept_emp as de on d.dept_no = de.dept_no
left join salaries as s on s.emp_no = de.emp_no
group by d.dept_no;
Copy the code
I think this is problematic because there is no direct contact between table salaries in the second left join and departments, the two tables are indirectly related through table DEPt_EMp, but it is over. I don’t know how to explain it.