2013-02-09 50 views
0

這是我正在嘗試的查詢。MySQL count()沒有返回正確的數字

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; 
+0

查詢的其餘部分是否工作併產生期望的結果集? – kabuto178 2013-02-09 02:52:27

+0

是的,其餘列包含有效值。只有'count(e.UserId)'列有錯誤的值。 – 2013-02-09 03:00:22

+0

請發佈樣本數據。 – 2013-02-09 06:00:43

回答

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;