开发者

complex(?) mysql correlated counting query. please help?

Suppose the following situation. Persons assigned to tasks, and I want to return Person id, Person Name, the number of tasks completed by each person from the following tables.

Table Name - Field Name

Person - id, Name

Task_Person_Combi - Task_id, Person_id

Task* - returns id of Task (actually this is LEFT Joined table which returns id of persons) (Task has over 100,000 rows, and the query has to be quick well less than 1 second)

After reading MySQL statement combining a join and a count?, I'm trying the following. (but this doesn't seem to work, and I'm kind of lost)

SELECT id, Name,
(
    SELECT COUNT(*)
    FROM Task_Person_Combi C
    WHERE P.id=C.Person_id AND C.Task IN开发者_如何学编程 (SELECT id FROM Task* - this is Joined table)
) AS Count
FROM Person P
WHERE id>0
HAVING Count>0
ORDER BY Name

Please help.


Try this?

SELECT id, Name,
      COUNT(T.ID)  AS TaskCount

FROM Person AS P
INNER JOIN Task_Person_Combi AS C ON  P.id=C.Person_id 
LEFT JOIN TASK AS T ON C.Task = T.id
WHERE id>0
AND T.id IS NOT NULL
GROUP BY id,Name
HAVING COUNT(T.ID)>0
ORDER BY Name
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜