如何计算连接表记录

时间:2017-04-21 02:26:12

标签: mysql

老实说,对我的案子提出正确的问题......

假设我有两张桌子,

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    |

我的问题是如何显示所有记录,并计算参与时间_发布时间,大致如下:

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

但是在我尝试了我的查询后,我得到了这样的结果:

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

请帮我解决我的情况,谢谢

*注意:如果您知道查询并知道如何在雄辩的laravel上使用它,那就更好了

1 个答案:

答案 0 :(得分: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