2017-04-21 78 views
0

老實說,IDK的在我的情況下,正確的問題...怎麼算連接表記錄

比方說,我有2個表,

Table User     Table Attendance 

|id|name|address|   |id|user_id|attendance_status| 
-----------------   ------------------------------ 
|1 |July|NY City|   |1 | 1 |  Late  | 
|2 |Remy|London |   |2 | 2 |  On Time | 
|3 |Mike|Turin |   |3 | 2 |  On Time | 
          |4 | 3 |  On Time | 
          |5 | 3 |  On Time | 
          |6 | 3 |  On Time | 

我的問題是如何顯示與計數attendance_status所有記錄準時,approxiately這樣的:

|user_id|name|total| 
-------------------- 
| 1 |July| 0 | 
| 2 |Remy| 2 | 
| 3 |Mike| 3 | 

但之後,我想我的查詢,我得到這樣的:

|user_id|name|total| 
-------------------- 
| 2 |Remy| 2 | 
| 3 |Mike| 3 | 

請幫我解決我的情況下,由於

*注:如果你知道的查詢,並知道如何使用它雄辯laravel,那最好不過了

回答

0

嘗試此查詢:

SELECT 
    t1.id AS user_id, 
    t1.name, 
    COALESCE(t2.total, 0) AS total 
FROM User t1 
LEFT JOIN 
(
    SELECT user_id, COUNT(*) AS total 
    FROM Attendance 
    WHERE attendance_status = 'On Time' 
    GROUP BY user_id 
) t2 
    ON t1.id = t2.user_id 

演示在這裏:

SQLFiddle

+0

哎呀,我沒有意識到你已經從'INNER JOIN'將查詢變成'LEFT JOIN':D,謝謝bud – DarkCode999