MySQL选择4个联接表的值

时间:2018-09-19 17:56:14

标签: mysql sql join

我正在尝试获取所有标题为“高级员工”且在财务部门工作的员工的名字,姓氏,起始日期和结束日期。

员工:

# emp_no, birth_date, first_name, last_name, gender, hire_date
'10001', '1953-09-02', 'Georgi', 'Facello', 'M', '1986-06-26'
'10002', '1964-06-02', 'Bezalel', 'Simmel', 'F', '1985-11-21'
'10003', '1959-12-03', 'Parto', 'Bamford', 'M', '1986-08-28'

employees.departments

# dept_no, dept_name
'd002', 'Finance'
'd003', 'Human Resources'

employees.dept_manager

# emp_no, dept_no, from_date, to_date
'110022', 'd001', '1985-01-01', '1991-10-01'
'110039', 'd001', '1991-10-01', '9999-01-01'

employees.titles

# emp_no, title, from_date, to_date
'10001', 'Senior Engineer', '1986-06-26', '9999-01-01'
'10002', 'Staff', '1996-08-03', '9999-01-01'

当前输入

SELECT emps.first_name,emps.last_name, t.title, start_date, end_date
FROM employees emps INNER JOIN
     employees.dept_manager dm INNER JOIN
     employees.titles t INNER JOIN
     employees.departments d
     ON t.emp_no = emps.emp_no
WHERE t.title = 'Senior Staff' and d.dept_name = 'Finance' ;

这导致错误1052:列中的from_date不明确

关于获得正确输出的任何建议?

1 个答案:

答案 0 :(得分:0)

如果其他表具有相同的列名,则需要表alias

第二,您当前的查询有许多错误的语法,例如JOIN,没有ON子句。因此,正确的版本应如下所示:

SELECT emps.first_name,emps.last_name, t.title, t.start_date, t.end_date
------------------------------------------------^-------------^
FROM employees emps INNER JOIN
     employees.dept_manager dm 
     ON emps.emp_no = dm.emp_no INNER JOIN
     employees.titles t 
     ON t.emp_no = emps.emp_no INNER JOIN
     employees.departments d
     ON d.dept_no = dm.dept_no
WHERE t.title = 'Senior Staff' and d.dept_name = 'Finance';