2016-05-09 83 views
0

數據庫表:優化MySQL查詢(生成統計)

enter image description here

enter image description here

我有MySQL查詢:

select calendar.datefield AS date, 
     (SELECT IFNULL(SUM(visits),0) 
      FROM link_stats 
      WHERE link_stats.link_id = '1' 
       AND statDate = date 
    ) AS visits, 
     (SELECT Round(IFNULL(SUM(leads * (rate/1000)),0),3) 
      FROM link_stats 
      WHERE link_stats.link_id = '1' 
       AND statDate = date 
    ) AS cash, 
     (SELECT IFNULL(SUM(leads),0) 
      FROM link_stats 
      WHERE link_stats.link_id = '1' 
       AND statDate = date 
    ) AS leads 
    from `calendar` 
    where `calendar`.`datefield` between '2016-05-10' AND '2016-05-11' 

我嘗試生成空白天數鏈接統計報告。

例子:

之間2016年11月1日至20-01-2016和鏈接不具有日期2016年12月1日的記錄。

回答

0

建立一個包含所有可能日期的表格。說它TableOfDates,並有一列:的DateField

然後重新查詢是這樣的:

select d.datefield AS date, 
     ls.visits, ls.cash, ls.leads 
    from TableOfDates d 
    LEFT JOIN `calendar` AS c ON c.datefield = d.datefield 
    LEFT JOIN 
     (SELECT statDate, 
       IFNULL(SUM(visits),0) AS visits, 
       Round(IFNULL(SUM(leads * (rate/1000)), 0),3) AS cash, 
       IFNULL(SUM(leads),0) AS leads 
      FROM link_stats 
      WHERE ls.link_id = 1 
       AND statDate between '2016-01-11' AND '2016-01-20' 
      GROUP BY statDate 
    ) AS ls ON ls.statDate = d.datefield 
    where d.datefield  between '2016-01-11' AND '2016-01-20'