2012-05-23 39 views
1

我有一個查詢,疑慮連接 - MySQL的

SELECT E.staffid AS staff 
SUM(E.Frequency='Less') AS lessCount, 
SUM(E.Frequency='More') AS moreCount, 
FROM effort_frequency E 
INNER JOIN ost_staff S ON S.staff_id = E.staffid 
WHERE E.log_date BETWEEN '2012-05-01' AND '2012-05-23' 
GROUP BY E.staffid 

我得到下面的表,

+-------+-----------+-----------+ 
| Staff | lessCount | moreCount | 
+-------+-----------+-----------+ 
| 1 | 2  |  3  | 
| 3 | 1  |  4  | 
| 5 | 2  |  3  | 
+-------+-----------+-----------+ 

你可以看到,2 & 4在結果缺失,將會有沒有行 with staff_id 2 & 4在effort_frequency表中給定的日期,但我想加入ost_staff表,這樣我就可以得到類似下面的表,ost_staff將包含所有員工ID,讓我們說1-5。

+-------+-----------+-----------+ 
| Staff | lessCount | moreCount | 
+-------+-----------+-----------+ 
| 1 | 2  |  3  | 
| 2 | 0  |  0  | 
| 3 | 1  |  4  | 
| 4 | 0  |  0  | 
| 5 | 2  |  3  | 
+-------+-----------+-----------+ 

我試過外連接,但它不工作,我想我在某個地方犯了錯誤。

回答

2

WHERE子句移動到ON子句,並將INNER JOIN更改爲RIGHT JOIN。並將GROUP BY E.staffid更改爲GROUP BY S.staff_id;同樣與SELECT E.staffid,將其更改爲SELECT s.staff_id

SELECT S.staff_id AS staff 

    COALESCE(SUM(E.Frequency='Less'),0) AS lessCount, 
    COALESCE(SUM(E.Frequency='More'),0) AS moreCount, 

FROM effort_frequency E 

RIGHT JOIN ost_staff S 
ON S.staff_id = E.staffid 
AND E.log_date BETWEEN '2012-05-01' AND '2012-05-23' 

GROUP BY S.staff_id 

如果你想使用LEFT JOIN,切換表ost_staff和effort_frequency:

SELECT S.staff_id AS staff 

    COALESCE(SUM(E.Frequency='Less'),0) AS lessCount, 
    COALESCE(SUM(E.Frequency='More'),0) AS moreCount, 

FROM ost_staff S 

LEFT JOIN effort_frequency E 
ON S.staff_id = E.staffid 
AND E.log_date BETWEEN '2012-05-01' AND '2012-05-23' 

GROUP BY s.staff_id 

也可以代替COALESCE的使用IFNULL。 IFNULL只適用於MySQL,雖然

+0

這工作,我試圖,我得到了結果,非常感謝:) –

1

你試過LEFT JOIN

SELECT E.staffid AS staff 
     COALESCE(SUM(E.Frequency='Less'),0) AS lessCount, 
     COALESCE(SUM(E.Frequency='More'),0) AS moreCount, 
FROM effort_frequency E LEFT JOIN ost_staff S 
     ON S.staff_id = E.staffid 
WHERE E.log_date BETWEEN '2012-05-01' AND '2012-05-23' 
GROUP BY E.staffid 

Article to Learn SQL JOINS

COALESCE加入,因爲它會返回NULL 如果沒有記錄存在。

+0

你的也很有幫助,我試過正確加入和它的工作。非常感謝:) –