gpt4 book ai didi

php - CodeIgniter 连接花费的时间太长,但单独的查询是即时的

转载 作者:行者123 更新时间:2023-11-29 18:58:22 25 4
gpt4 key购买 nike

我正在编写一个系统,该系统能够搜索中型数据库,检查多个表中的搜索查询。只是为了让您了解数据库的规模:

客户表

行数:13396

Customer_domains 表

行数:13373

它们是我尝试使用此查询搜索的仅有的两个表。

问题

我面临的问题是,通过使用使用 joins 的查询,加载时间超过 2 分钟才能完成搜索。

通过运行两个单独的查询并返回它们的组合结果几乎是即时的。

通过运行两个单独的查询而不是联接,我可以在合理的时间范围内获得搜索结果但是使用此方法我无法正确实现分页,因为我可以执行两个单独的查询'不要应用一个限制。

因此,执行此操作的正确方法似乎是使用联接,但为什么联接花费的时间比第二个查询要长得多?

使用联接的我的代码(执行时间太长)

public function search($searchquery)
{
$this->db->select()
->from('customers')
->join('customer_domains', 'customer_domains.customer_id = customers.customer_id')
->like('customers.customer_id', $searchquery, 'both')
->or_like('customers.customer_name', $searchquery, 'both')
->or_like('customers.business_name', $searchquery, 'both')
->or_like('customers.address_line_1', $searchquery, 'both')
->or_like('customers.address_line_2', $searchquery, 'both')
->or_like('customers.address_line_3', $searchquery, 'both')
->or_like('customers.address_line_4', $searchquery, 'both')
->or_like('customers.postcode', $searchquery, 'both')
->or_like('customers.landline', $searchquery, 'both')
->or_like('customers.mobile', $searchquery, 'both')
->or_like('customers.email', $searchquery, 'both')
->or_like('customer_domains.domain', $searchquery, 'both')
->limit(50);
$query = $this->db->get();

$result = $query->result();

return $result;

}

我的代码有两个单独的查询(无法分页)

public function search($searchquery)
{
$this->db->select()
->from('customers')
->like('customers.customer_id', $searchquery, 'both')
->or_like('customers.customer_name', $searchquery, 'both')
->or_like('customers.business_name', $searchquery, 'both')
->or_like('customers.address_line_1', $searchquery, 'both')
->or_like('customers.address_line_2', $searchquery, 'both')
->or_like('customers.address_line_3', $searchquery, 'both')
->or_like('customers.address_line_4', $searchquery, 'both')
->or_like('customers.postcode', $searchquery, 'both')
->or_like('customers.landline', $searchquery, 'both')
->or_like('customers.mobile', $searchquery, 'both')
->or_like('customers.email', $searchquery, 'both')
->limit(50);
$query = $this->db->get();

$result = $query->result();

$this->db->select('')
->from('customer_domains')
->join('customers', 'customers.customer_id = customer_domains.customer_id', 'left')
->like('customer_domains.domain', $searchquery, 'both')
->limit(50);
$query_domains = $this->db->get();

foreach($query_domains->result() as $query_domain){
array_push($result, $query_domain);
}

return $result;

}

是否有人对此有其他解决方案,或者也许可以解释为什么更好的 join 语句比第二个查询花费的时间长得多以及如何改进?谢谢!

最佳答案

为了使查询速度更快,您应该从表中添加索引

https://dev.mysql.com/doc/refman/5.7/en/mysql-indexes.html

关于php - CodeIgniter 连接花费的时间太长,但单独的查询是即时的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44020514/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com