0

I have a table like the following one:

 id   user_id    task    task_closed 
  1       1       1         0
  2       1       2         1
  3       1       3         0
  4       2       3         0 
  5       2       4         1
  6       3       4         0

What I need is a query that for a given task will return all the uses that have this task and for each of them the number of overall un-closed tasks they have.

so that if we are talking about task 3 I want to get

user_id  pending
   1        2
   2        1

as in

SELECT tasks.user_id,
       ( SELECT COUNT(*) 
         FROM tasks t2 
         WHERE t2.user_id=tasks.user_id AND t2.task_closed=0
       )
FROM tasks
WHERE tasks.id=?

I would also re-write this as

  SELECT user_id,COUNT(*) 
  FROM tasks  
  WHERE task=? AND task_closed=0 
  GROUP_BY user_id
  WHERE user_id IN (SELECT t2.user_id from tasks t2 WHERE task=?); 

But I have a strong feeling that there should be a more efficient way to do this by somehow joining the table with itself.

any ideas on how I should do that ?

4

3 回答 3

1

试试这个查询

SELECT 
   b.userid,
   count(*) as cnt
FROM 
   (SELECT DISTINCT userId FROM tasks WHERE task=?) a
INNER JOIN 
   tasks b
ON
   a.userId=b.userid
WHERE 
   b.task_closed = 0
GROUP BY 
   b.userid

这将复制你所做的。但我对你的查询感到困惑。您正在计算所有任务的任务关闭,但您只需要用户给出的任务的结果。

于 2013-05-27T08:10:05.777 回答
0

尝试这个:

SELECT 
    t1.user_id,
    COUNT(*)
FROM 
    tasks t1
INNER JOIN tasks t2
    ON t2.user_id=t1.user_id 
    AND t2.task_closed=0
WHERE 
    t1.id=?

但是假设任务的 id 是taskcolumn 而不是idcolumn(因为 id 是唯一的,这意味着对于 1 个任务,您不再有一个用户)

SELECT 
    t1.user_id,
    COUNT(*)
FROM 
    tasks t1
INNER JOIN tasks t2
    ON t2.user_id=t1.user_id 
    AND t2.task_closed=0
WHERE 
    t1.task=?
GROUP BY
    t1.user_id

更新:如果您想从上面加入查询结果以获取其他信息,例如:一些用户详细信息(表中field的列user_details),您可以使用:

SELECT
    tmp.user_id,
    tmp.nb,
    user_details.field
FROM (
    SELECT 
        t1.user_id,
        COUNT(*) as nb
    FROM 
        tasks t1
    INNER JOIN tasks t2
        ON t2.user_id=t1.user_id 
        AND t2.task_closed=0
    WHERE 
        t1.task=?
    GROUP BY
        t1.user_id
) as tmp
LEFT JOIN user_details
    ON user_details.user_id = tmp.user_id
于 2013-05-27T07:53:55.563 回答
0

我认为这会起作用:

从 tasks.task=? 的任务中选择 tasks.user_id,count(*) 和 task_closed=0 按 user_id 分组

于 2013-05-27T08:00:42.870 回答