创建查询时遇到问题,该查询返回列出每位员工及其经理的结果集。
如果您熟悉员工数据库,您知道他们是员工表,dept_manager表和dept_emp表,您可以在其中链接前两个表。
我的结果集只为每个人和一个部门返回一个经理。
我感谢任何帮助!
SELECT d.dept_name AS 'Dept',
CONCAT(em.last_name, ' ', em.first_name) AS 'Manager last, first',
CONCAT(e.last_name,' ', e.first_name, ' ', t.title) AS 'Employee last, first (title)'
FROM dept_manager AS dm
LEFT JOIN dept_emp AS de ON de.dept_no = dm.dept_no
LEFT JOIN departments AS d ON d.dept_no = dm.dept_no
LEFT JOIN employees AS e ON e.emp_no = de.emp_no
LEFT JOIN employees AS em ON em.emp_no = dm.emp_no
LEFT JOIN titles AS t ON t.emp_no = e.emp_no
WHERE
dm.emp_no = e.emp_no
AND
dept_name = 'Sales'
OR
dept_name = 'Marketing'
AND
dm.to_date >= '2012-05-07'
AND
t.to_date > '2012-05-07'
AND
de.to_date > '2012-05-07'
ORDER BY e.last_name, e.first_name
limit 1000
答案 0 :(得分:2)
尝试
SELECT d.dept_name department,
CONCAT(e.first_name, ' ', e.last_name, ', ', t.title) employee,
CONCAT(m.first_name, ' ', m.last_name) manager
FROM employees e JOIN
titles t ON e.emp_no = t.emp_no JOIN
dept_emp de ON e.emp_no = de.emp_no JOIN
departments d ON de.dept_no = d.dept_no JOIN
dept_manager dm ON dm.dept_no = de.dept_no JOIN
employees m ON dm.emp_no = m.emp_no
WHERE (d.dept_name = 'Sales'
OR d.dept_name = 'Marketing')
AND dm.to_date >= '2012-05-07'
AND t.to_date > '2012-05-07'
AND de.to_date > '2012-05-07'
ORDER BY employee
LIMIT 1000
在AND
子句中合并OR
和WHERE
时,请始终使用括号。
答案 1 :(得分:0)
我不确定这个sql是否可以提供帮助,我没有得到标题,但我认为它可以包含在第二个子查询中。 整个想法是我们将首先尝试获取emp_id和manager_id,在此基础上,我们将通过子查询获取相关信息。
SELECT (SELECT dept_name FROM departments WHERE dept_no = de.dept_no)
, (SELECT CONCAT(last_name, ' ', first_name) FROM employees WHERE emp_no = de.emp_no)
, (SELECT CONCAT(last_name,' ', first_name) FROM employees WHERE emp_no = dm.manager_no)
FROM dept_emp de
INNER JOIN dept_manager dm ON de.dept_no = dm.dept_no