索引此SQL查询以获得最佳优化

时间:2015-08-05 06:04:00

标签: mysql optimization

在现有项目中,我在phpmyadmin中有一个数据库,从长远来看,数据库应该包含大量数据。我经常需要为客户绘制年度报告,当我绘制报告时,数据库中的总记录大约为950,000,搜索时间大约为15秒,到目前为止非常令人满意,但是当我在数据库中插入400,000多个测试数据时搜索时间从15秒跃升至令人沮丧的2.08分钟。 我试图在没有任何差异的情况下运行碎片整理和优化操作。

我注意到这个表没有编入索引(因为它应该是根据一些谷歌的搜索)我想建议如何最好地索引表,因为我是新手索引。

这是查询。

            $currentuserid = $this->session->userdata('userid');
$year='2008';
            $query = $this->db->query("     
select  customers.id,customers.customername,
      sum(if( MONTH(keyslog.timestamp) = 1,  keyslog.count, 0 )) as January,
      sum(if( MONTH(keyslog.timestamp) = 2,  keyslog.count, 0 )) as February,
      sum(if( MONTH(keyslog.timestamp) = 3,  keyslog.count, 0 )) as March,
      sum(if( MONTH(keyslog.timestamp) = 4,  keyslog.count, 0 )) as April,
      sum(if( MONTH(keyslog.timestamp) = 5,  keyslog.count, 0 )) as May,
      sum(if( MONTH(keyslog.timestamp) = 6,  keyslog.count, 0 )) as June,
      sum(if( MONTH(keyslog.timestamp) = 7,  keyslog.count, 0 )) as July,
      sum(if( MONTH(keyslog.timestamp) = 8,  keyslog.count, 0 )) as August,
      sum(if( MONTH(keyslog.timestamp) = 9,  keyslog.count, 0 )) as September,
      sum(if( MONTH(keyslog.timestamp) = 10, keyslog.count, 0 )) as October,
      sum(if( MONTH(keyslog.timestamp) = 11, keyslog.count, 0 )) as November,
      sum(if( MONTH(keyslog.timestamp) = 12, keyslog.count, 0 )) as December,
      sum(keyslog.count) as Total
    from  customers, keyslog, users_customer
    where  (YEAR(timestamp) = '$year')
      AND  customers.id = keyslog.customers
      AND  users_customer.custo_id = keyslog.customers
      AND  keyslog.active = '1'
      AND  users_customer.userID = '$currentuserid'
      AND  users_customer.checked='1'
    group by  customers.id,customers.customername

如我所知,我试图运行解释,这是结果,但我无法解释

id  select_type     table   type    possible_keys   key     key_len     ref     rows    Extra
1   SIMPLE  keyslog     ALL     NULL    NULL    NULL    NULL    1437493     Using where; Using temporary; Using filesort
1   SIMPLE  customers   eq_ref  PRIMARY,id  PRIMARY     4   iccid.keyslog.customers     1   
1   SIMPLE  users_customer  ref     userID,checked,userID_2     userID_2    12  const,iccid.customers.id,const  1   Using where; Using index

有关如何在哪些表上添加任何索引或如何更改查询以达到最佳最佳检索的任何建议都将非常感谢

我是否还应该专门定位我在查询中添加的索引 例如

from customers,keyslog,users_customer USE INDEX (PRIMARY) ?

1 个答案:

答案 0 :(得分:1)

users_customer:INDEX(userID, checked) - 除非userIDPRIMARY KEY keyslog:INDEX(customers)
客户:INDEX(id) - 除非已经PRIMARY KEY

而不是(YEAR(timestamp) = '$year'),请使用

timestamp >= '$year-01-01'  AND
timestamp  < '$year-01-01' + INTERVAL 1 YEAR

(优化器不够智能,不能用YEAR()做明显的事情。)

为清楚起见,请切换到JOIN...ON语法。

了解摘要表:http://mysql.rjweb.org/doc.php/summarytables