2013-05-08 75 views
0

無法創建查詢,該查詢返回列出每個員工及其經理的結果集。mysql樣本員工數據庫 - 返回員工及其經理的查詢

如果您熟悉員工數據庫,您知道他們是員工表,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 
+1

我不熟悉員工db ... – quickshiftin 2013-05-08 05:54:39

回答

1

嘗試

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 

,當你在WHERE條款結合ANDOR始終使用括號。

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