复杂(?)mysql相关计数查询。请帮忙?

时间:2011-08-24 01:23:20

标签: mysql

假设以下情况。 分配给任务的人员,我想从下表中返回人员ID,人员姓名,每个人完成的任务数。

表名 - 字段名称

人 - 身份,姓名

Task_Person_Combi - Task_id,Person_id

任务* - 返回Task的id(实际上这是返回人员ID的LEFT Joined表) (任务有超过100,000行,查询必须快速不到1秒)

阅读MySQL statement combining a join and a count?后,我正在尝试以下方法。 (但这似乎不起作用,我有点迷失了)

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

请帮忙。

1 个答案:

答案 0 :(得分:1)

试试这个?

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