date_format(from_unixtime())subselect非常慢

时间:2017-11-10 12:25:47

标签: mysql select indexing count

我有以下问题,我试图在日期范围内每天吐出并显示引导数,分配数和数量。返回:

select 
date_format(from_unixtime(date_created), '%m/%d/%Y') as date_format, 
(select count(distinct(id_lead)) from lead_history where (date_format(from_unixtime(date_created), '%m/%d/%Y') = date_format) and (id_vertical in (2)) and (id_website in (3,8))) as leads,
(select count(id) from assignments where deleted=0 and (date_format(from_unixtime(date_assigned), '%m/%d/%Y') = date_format) and (id_vertical in (2)) and (id_website in (3,8))) as assignments,
(select count(id) from assignments where deleted=1 and (date_format(from_unixtime(date_deleted), '%m/%d/%Y') = date_format) and (id_vertical in (2)) and (id_website in (3,8))) as returns 
from lead_history 
where date_created between 1509494400 and 1512086399 
group by date_format

date_createddate_assigneddate_deleted字段是表示时间戳的整数。 idid_leadid_verticalid_website已编入索引。

date_createddate_assigneddate_deleteddeleted添加索引会有助于加快速度吗?我遇到的问题是它非常慢,而且在使用date_format(from_unixtime(...

时,我不确定索引是否会有所帮助

以下是EXPLAIN

Imgur

1 个答案:

答案 0 :(得分:0)

查看代码,您可以将查询重写为..

  select 
      date_format(from_unixtime(date_created), '%m/%d/%Y') as date_format
      , count(distinct(h.id_lead) as leads
      , sum(case a.deleted = 1 then 1 else 0 end) assignments
      , sum(case b.deleted = 0 then 1 else 0 end) returns
  from lead_history  h 
  inner join assignments on  a a.date_assigned = h.date_created 
        and a.id_vertical = 2 
        and id_website in (3,8))
  inner join assignments on  b b.deleted = h.date_created 
        and a.id_vertical = 2 
        and id_website in (3,8))
  where date_created between 1509494400 and 1512086399 
  group by date_format

无论如何你应该避免使用unuseful()和嵌套(),避免在日期和使用连接之间进行无用的转换而不是使用subselect ..或者至少使用case减少类似的sabuselect

PS对于什么关注索引记住,使用转换对列值无效使用相关的索引..