如何提高Codeigniter中的MySQL查询性能?

时间:2015-04-02 03:34:02

标签: mysql performance codeigniter

我有这个MySQL查询,我正在加载到我的家庭控制器并运行Codeigniter的$searchterm = $this->search_model->searchterm_handler($this->input->get_post('searchterm', TRUE));后 我的执行时间为0.7110

我的模型中的查询:

<?php
class Search_Model extends CI_Model

    public function search($searchterm,$limit)
        {
            $sql = "SELECT cast(s.req_date as Date) as Date, SUM(s.sTransaction)+SUM(r.rTransaction) as SUMt, SUM(s.sSuccess)+ SUM(r.rSuccess) as SUMs, s.sTransaction, r.rTransaction, s.sSuccess, r.rSuccess
                    FROM
                    (SELECT s.req_date, COUNT(*) as sTransaction, SUM(s.status = 0) as sSuccess 
                    FROM transaction_log_ats_201503 as s WHERE cast(s.req_date as time) BETWEEN '00:00:00' AND '$searchterm'
                    GROUP BY cast(req_date as Date) desc) as s 
                    JOIN
                    (SELECT r.req_date, COUNT(*) as rTransaction, SUM(r.status = 0) as rSuccess 
                    FROM transaction_log_atr_201503 as r WHERE cast(r.req_date as time) BETWEEN '00:00:00' AND '$searchterm'
                    GROUP BY cast(req_date as Date) desc) as r 
                    ON cast(s.req_date as date)=cast(r.req_date as date)
                    GROUP BY Date desc";


            $q = $this->db->query($sql);
            if($q->num_rows() > 0)
            {
                foreach($q->result() as $row)
                {
                    $data[] = $row;
                }
                return $data;
            }
            else
            {
                return 0;
            }
        }
 ?>

是否有任何提升查询性能的方法?

感谢。

1 个答案:

答案 0 :(得分:0)

我认为你错过了&#34;)&#34;。

为什么子查询中有DESC;它无法控制任何有用的东西。

MySQL(直到5.6)无法优化 FROM ( SELECT ... ) JOIN ( SELECT ... ) ON ... 没有索引,所以它对tmp表执行全表扫描,因此速度很慢。

可能的解决方案:

  • 升级到5.6。
  • 将其中一个子查询放在TEMPORARY表中,并在reg_date上为其指定一个INDEX。