我一直在尝试编写一个sql查询来从bugzilla获取一些统计信息。这是查询
select bugs.bug_id AS bug_id,
COUNT(map_pingpong.bug_when) AS re_open,
MAX(map_closetime.bug_when) AS closed_date
from bugs
LEFT JOIN bugs_activity AS map_pingpong
ON ((map_pingpong.bug_id = bugs.bug_id
and map_pingpong.fieldid=15))
LEFT JOIN bugs_activity AS map_closetime
ON ((bugs.bug_id = map_closetime.bug_id
and map_closetime.fieldid=8
and bugs.bug_status = 'CLOSED' ))
where (bugs.assigned_to = 480)
GROUP BY bugs.bug_id
ORDER BY bug_id;
所以,查询应该返回两件事
1)发生事件的计数 2)事件发生的日期
因此,当我将查询分成两个不同的查询时,它们返回正确的值。如果我如上所述运行它,计数值是错误的(虽然日期是正确的)。我不应该在同一张桌子上运行两个连接?当你使用join时,或者count不应该在那里?
答案 0 :(得分:0)
正如Barmar所说,你必须分离结果集以获得正确的计数:
SELECT
bugs.bug_id AS bug_id,
map_pingpong.cnt AS re_open,
map_closetime.mx AS closed_date
FROM bugs
LEFT JOIN (
SELECT bug_id, COUNT(bug_when) AS cnt
FROM bugs_activity
WHERE fieldid = 15
GROUP BY bug_id
) AS map_pingpong ON map_pingpong.bug_id = bugs.bug_id
LEFT JOIN (
SELECT ba.bug_id, MAX(ba.bug_when) AS mx
FROM bugs_activity ba JOIN bugs ON bugs.bug_status = 'CLOSED' AND ba.bug_id = bug.bug_id AND bugs.assigned_to = 480
WHERE ba.fieldid = 8
GROUP BY ba.bug_id
) AS map_closetime ON bugs.bug_id = map_closetime.bug_id
WHERE bugs.assigned_to = 480
GROUP BY bugs.bug_id
ORDER BY bug_id;
从功能上来说这是正确的,在性能方面可能是一场彻底的灾难,所以要小心......