2016-06-09 53 views
1

我有兩個表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 

我認爲有些事情錯在這裏...

我wan't得到結果:

id name tasks_total 
1 Name1 2 
2 Name2 1 

謝謝!

回答

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

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