优化codeigniter查询,加入或在哪里

时间:2015-06-12 11:09:37

标签: php mysql performance codeigniter query-optimization

我对CI比较新,我读到使用join可能会减慢报告速度,在我的数据库中会有超过100k的记录。我在CI中写了这两个查询,但没有注意到很多不同。我想知道我是否正确地编写了这些查询,或者是否有更好的方法来获得这样的查询,遗憾的是我不知道如何在类似结构的样本中发布这些查询。

function select_data_specific_customer($from, $to, $customer, $threshold = '') {

        //die($from);
        $currentuserid = $this->session->userdata('userid');
        $this->db->select('timestamp');
        $this->db->select('count');
        $this->db->select('price');
        $this->db->select('totalPrice');
        $this->db->select('reference');
        $this->db->select('customers_r');
        $this->db->select('userID_r');
        $this->db->from('logger');
        $this->db->from('users_customer');
        $this->db->where(array('users_customer.custo_id' => "logger.customers"), NULL, FALSE);      
        //users_customer contains connection between users and customers (  id  userID  custo_id    checked )
        $this->db->where(array('users_customer.userID' => $currentuserid), NULL, FALSE);
        $this->db->where(array('users_customer.checked' => '1'), NULL, FALSE);
        $this->db->where('cast(timestamp as date) BETWEEN "' . date('Y-m-d', strtotime(str_replace('-', '/', $from))) . '" and "' . date('Y-m-d', strtotime(str_replace('-', '/', $to))) . '"');


        $query = $this->db->get();

        if ($query->num_rows() > 0) {
            foreach ($query->result() as $row) {
                $data[] = $row;
            }

            return $data;
        }

        return false;
    }

这是第二个功能

function select_data_specific_customer($from, $to, $customer, $threshold = '') {

        //die($from);
        $currentuserid = $this->session->userdata('userid');
         $this->db->select('timestamp');
        $this->db->select('count');
        $this->db->select('price');
        $this->db->select('totalPrice');
        $this->db->select('reference');
        $this->db->select('customers_r');
        $this->db->select('userID_r');
        $this->db->from('logger');
        $this->db->join("users_customer", "users_customer.custo_id=logger.customers", 'inner');
        $this->db->where(array('users_customer.userID' => $currentuserid), NULL, FALSE);
        $this->db->where(array('users_customer.checked' => '1'), NULL, FALSE);
        $this->db->where('cast(timestamp as date) BETWEEN "' . date('Y-m-d', strtotime(str_replace('-', '/', $from))) . '" and "' . date('Y-m-d', strtotime(str_replace('-', '/', $to))) . '"');


        $query = $this->db->get();

        if ($query->num_rows() > 0) {
            foreach ($query->result() as $row) {
                $data[] = $row;
            }

            return $data;
        }

        return false;
    }

我想知道是否有更优化的方式来编写相同的查询,因为此时这两个函数都需要大约6秒来显示。 结果可以增长到超过20万,并且时间可能会增加以显示它。

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

return $this->db->query("your query here");

您是否尝试过上述查询,并使用*来选择