我是否可以更改此查询,以便像COUNT(WHERE type_id = 2) AS success, COUNT(WHERE type_id = 1) AS error
一样阻止使用子查询?
SELECT
(SELECT COUNT(id) FROM log AS success_log WHERE type_id = 2 AND site_id = site.id AND DAYOFYEAR(success_log.created)) AS success,
(SELECT COUNT(id) FROM log AS success_log WHERE type_id = 1 AND site_id = site.id AND DAYOFYEAR(success_log.created)) AS error,
(SELECT COUNT(id) FROM log AS success_log WHERE site_id = site.id AND DAYOFYEAR(success_log.created)) AS total,
DATE_FORMAT(log.created, "%m-%d-%y") AS `day`
FROM log
WHERE site_id = ?
GROUP BY DAYOFYEAR(created)`
答案 0 :(得分:1)
您可以对GroupBy TypeId使用单计数,并将它们插入临时表中,然后选择您想要的方式。
答案 1 :(得分:0)
因为他们都是从同一站点的日志表中查询,所以你可以直接运行表ONCE并在一个总和中应用和IMMEDIATE IF()测试....如果记录属于给定类型, count为1,否则为0 ...获取类型1或类型2的总和,简单计数(*)获取相关日期的总计数。
SELECT
DATE_FORMAT(log.created, "%m-%d-%y") AS `day`,
sum( if( type_id = 2, 1, 0 )) as NumberSuccess,
sum( if( type_id = 1, 1, 0 )) as NumberError,
count(*) as TotalRecords
from
log
where
site_id = ?
group by
DAYOFYEAR(created)