简体   繁体   English

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

[英]MySQL count() not returning correct number

This is the query I'm trying. 这是我正在尝试的查询。

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) gives the same result as count(t.TaskId) which is wrong. count(e.UserId)给出相同的结果作为count(t.TaskId)这是不对的。 But count() returns the correct results if I run the query without any joins, for example: 但是,如果我在没有任何联接的情况下运行查询, count()将返回正确的结果,例如:

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

Not sure this will help but do you get desired result if you run below query - see group by: 不确定这是否有帮助,但是如果您在查询下面运行,是否会得到理想的结果-请参阅分组依据:

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

Just checking the query - noticed join between Tasks and Experiments tables is on ExperimentId - where in the query that you state you get the desired result only userId is used. 只需检查查询-注意到Tasks和Experiments表之间的联接在ExperimentId上-在您声明的查询中,您仅使用userId即可获得所需的结果。 Let me know if this helps. 让我知道是否有帮助。

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM