2011-09-24 46 views
1

是否可以更改此查詢,以便我可以像COUNT(WHERE type_id = 2) AS success, COUNT(WHERE type_id = 1) AS error一樣來防止使用子查詢?MySQL優化 - 防止子查詢

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

看看sum(if ...或sum(case when when syntax) –

回答

1

您可以使用單數用的GroupBy TYPEID並在臨時表中插入它們,然後選擇您想要的方式。

0

因爲它們都是從日誌表中查詢同一個站點,所以只需要運行表ONCE並且只需應用IMMEDIATE IF()測試就可以了....如果記錄是給定類型的,計爲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)