数据库查询执行时间过长

时间:2016-06-19 05:14:11

标签: php mysql sql codeigniter

我目前遇到此问题,我的数据库查询执行时间太长,有时会因错误而失败:超出最大执行时间...我试图从不直接与之相关的不同表中选择数据彼此,即一个表与一个与另一个表相关的表相关等等,这些表中有一些有超过一千条记录,我感觉不同表的结构导致了这个头痛,但我没有&# 39;能够弄清楚如何减少执行时间。我使用CodeIgniter模型,我使用以下sql查询创建了一个函数:

/**
* Get payment history based on search term
* @param string $search
* @param int $limt => default is 10
* @return mixed
**/

public function get_search_history($usertin, $search, $limit, $offset){

    $this->db->select("
            rv.name AS 'Revenue Name',rv.code AS 'Rev. Code',
            m.name AS 'MDA',m.sector AS 'Sector', b.code AS 'Bank Code',
            b.name AS 'Bank',p.amount AS 'Amount',p.channel AS 'Payment Channel',
            p.date AS 'Payment Date',p.platform AS 'Platform',p.ref AS 'Reference',
            t.tin AS 'TIN',t.active AS 'Is Active?',r.ref AS 'Receipt Reference'
        ");

    $this->db->from('revenue AS rv');
    $this->db->join('mda AS m', 'm.id = rv.mda_id', 'inner');
    $this->db->join('payment AS p', 'p.revenue_id = rv.id', 'inner');
    $this->db->join('bank AS b', 'b.id = p.bank_id', 'inner');
    $this->db->join('tin AS t', 't.id = p.tin_id', 'inner');
    $this->db->join('receipt AS r', 'r.id = p.receipt', 'inner');
    $this->db->where('t.tin', $usertin);
    $this->db->like('rv.code', $search);
    $this->db->or_like('rv.name', $search);
    $this->db->or_like('m.name', $search);
    $this->db->group_by('t.id');
    $this->db->order_by('p.date', 'ASC');
    $this->db->limit($limit, $offset);

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

    return ( ( $query->num_rows() > 0 ) ? $query->result_array() : 0 );

}

该查询应根据特定搜索字词或关键字检索用户的付款记录!

从上面的查询中可以更容易地看出我说的时候我的意思" ...一张表与一张与另一张表相关的表有关..."我无法找到更好的方法。谁能帮我吗?在过去的几天里,它给了我严重的头痛!

这是查询的输出:

SELECT rv.name AS 'Revenue Name', rv.code AS 'Rev. Code', m.name AS
'MDA', m.sector AS 'Sector', b.code AS 'Bank Code', b.name AS 'Bank',
p.amount AS 'Amount', p.channel AS 'Payment Channel', p.date AS 'Payment
Date', p.platform AS 'Platform', p.ref AS 'Reference', t.tin AS 'TIN',
t.active AS 'Is Active?', r.ref AS 'Receipt Reference'
FROM `revenue` AS `rv`
INNER JOIN `mda` AS `m` ON `m`.`id` = `rv`.`mda_id`
INNER JOIN `payment` AS `p` ON `p`.`revenue_id` = `rv`.`id`
INNER JOIN `bank` AS `b` ON `b`.`id` = `p`.`bank_id`
INNER JOIN `tin` AS `t` ON `t`.`id` = `p`.`tin_id`
INNER JOIN `receipt` AS `r` ON `r`.`id` = `p`.`receipt`
WHERE `t`.`tin` = '1904260529-0001'
AND  `rv`.`code` LIKE '%With%' ESCAPE '!'
OR  `rv`.`name` LIKE '%With%' ESCAPE '!'
OR  `m`.`name` LIKE '%With%' ESCAPE '!'
GROUP BY `t`.`id`
ORDER BY `p`.`date` ASC
LIMIT 3, 20

1 个答案:

答案 0 :(得分:0)

如果您经常加入这么多表格,我可以提出两种可能的建议方式。

1。使用CodeIgniter的功能查询缓存

  • 您只需要从database.php启用它,并且必须为其提供所有缓存查询所在的文件夹路径。
  • 然后,您可以创建钩子或其他东西来删除并重新生成特定条件下的缓存查询。

2。在MySQL中创建视图

  • 您可以在MySQL中创建View,速度会快得多。它甚至可以从PHPMyAdmin轻松完成。

希望这有帮助。

<强> P.S。尝试索引正确的列。

简单的拇指规则是WHERE子句中的更多条件,因为较低的查询将是