- ~
題目描述
獲取全部員工的emp_no、部門編號dept_no以及對應的bonus類型btype和recevied,沒有分配具體的員工不顯示
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 dept_manager
(dept_no
char(4) NOT NULL,emp_no
int(11) NOT NULL,from_date
date NOT NULL,to_date
date NOT NULL,
PRIMARY KEY (emp_no
,dept_no
));
CREATE TABLE employees
(emp_no
int(11) NOT NULL,birth_date
date NOT NULL,first_name
varchar(14) NOT NULL,last_name
varchar(16) NOT NULL,gender
char(1) NOT NULL,hire_date
date NOT NULL,
PRIMARY KEY (emp_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
));spa
本題嚴謹的思路爲,先將 employees與dept_emp 用 INNER JOIN 鏈接,挑選出分配了部門的員工,再用 LEFT JOIN 鏈接 emp_bonus(在前面的題中可看到此表),分配了獎金的員工顯示獎金類型和授予時間,沒分配獎金的員工則不顯示。 SELECT em.emp_no, de.dept_no, eb.btype, eb.recevied FROM employees AS em INNER JOIN dept_emp AS de ON em.emp_no = de.emp_no LEFT JOIN emp_bonus AS eb ON de.emp_no = eb.emp_no 因爲dept_emp表中都是已分配部門的員工,所以只用 dept_emp表與emp_bonus表就能夠解決問題: SELECT de.emp_no, de.dept_no, eb.btype, eb.recevied FROM dept_emp AS de LEFT JOIN emp_bonus AS eb ON de.emp_no = eb.emp_no