来自两个表的Mysql请求计数

时间:2016-06-09 21:08:46

标签: php mysql

我有两张桌子

**users**

id name
1  Name1
2  Name2

**tasks**

id user_id title
1  1       Task1 
2  1       Task2                                    
3  2       Task3

我的要求:

SELECT 
    U.*,
    COUNT(T.id) AS tasks_total 
FROM 
    `#__users` AS U
LEFT JOIN
    `#__tasks` AS T
ON
    U.id = T.user_id

我认为这里有问题......

我想要得到结果:

id name  tasks_total
1  Name1 2
2  Name2 1

谢谢!

2 个答案:

答案 0 :(得分:1)

您忘记按ID

对结果进行分组
SELECT 
    U.*,
    COUNT(T.id) AS tasks_total 
FROM 
    `#__users` AS U
LEFT JOIN
    `#__tasks` AS T
ON
    U.id = T.user_id
group by U.id

demo on sqlfiddle

答案 1 :(得分:0)

您正在混合线功能和聚合功能。解决此问题的一种方法是在子查询中完成聚合:

SELECT 
    U.*,
    tasks_total 
FROM 
    `#__users` AS U
LEFT JOIN
    (SELECT   user_id, COUNT(*) AS tasks_total 
     FROM     `#__tasks` 
     GROUP BY user_id) AS T
ON
    U.id = T.user_id