1

在创建返回列出每个员工及其经理的结果集的查询时遇到问题。

如果您熟悉员工数据库,您就知道他们是一个员工表、一个 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
4

2 回答 2

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组合和ORinWHERE子句时始终使用括号。

于 2013-05-08T06:36:34.367 回答
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
于 2013-05-08T06:07:58.030 回答