MySQL count()没有返回正确的数字

时间:2013-02-09 02:25:50

标签: mysql

这是我正在尝试的查询。

select
    UserId,
    count(e.UserId) as 'Experiments',
    count(t.TaskId) as 'Tasks tried',
    count(case when t.TaskStatus = 'Completed' then t.TaskStatus end) as 'Tasks completed',
    sec_to_time(avg(timediff(TaskLocalUserEndDateTime,TaskLocalUserStartDateTime))) as 'Average Time'
from
    Tasks as t,
    Experiments as e
where
    t.ExperimentId = e.ExperimentId
and
    e.UserId = e.UserId
group by
    UserId;

count(e.UserId)给出与count(t.TaskId)相同的结果,这是错误的。但是,如果我在没有任何连接的情况下运行查询,count()会返回正确的结果,例如:

select
    count(UserId)
from
    Experiments
where
    UserId = UserId
group by 
    UserId;

1 个答案:

答案 0 :(得分:0)

不确定这会有所帮助,但如果您运行以下查询,您会获得所需的结果 - 请参阅分组依据:

select
    count(UserId), ExperimentId
from
    Experiments
where
    UserId = UserId
group by 
    ExperimentId;

只是检查查询 - 注意到任务和实验表之间的连接在ExperimentId上 - 在您声明的查询中,您只能使用userId获得所需的结果。如果这有帮助,请告诉我。

select
    UserId,
    e.Experiments, -- count(e.UserId) as 'Experiments',
    count(t.TaskId) as 'Tasks tried',
    count(case when t.TaskStatus = 'Completed' then t.TaskStatus end) as 'Tasks completed',
    sec_to_time(avg(timediff(TaskLocalUserEndDateTime,TaskLocalUserStartDateTime))) as 'Average Time'
from
    Tasks as t,
--    Experiments as e 
LEFT JOIN 
(
   select count(UserId) as 'Experiments', ExperimentId from Experiments group by ExperimentId
) as e
where
    t.ExperimentId = e.ExperimentId
and
    e.UserId = e.UserId
group by
    UserId;