gpt4 book ai didi

mysql - Laravel 中简单查询的查询检索时间较长

转载 作者:行者123 更新时间:2023-11-29 10:26:37 25 4
gpt4 key购买 nike

我在 Laravel 中编写了一个查询:

$policy = DB::table('policies')->
join('customers','policies.customer_id','=','customers.id')->
join('cities','customers.city_id','=','cities.id')->
join('policy_motors','policies.id','=','policy_motors.policy_id')->
join('vehicle_makes','policy_motors.vehicle_make','=','vehicle_makes.id')->
join('vehicle_models','policy_motors.vehicle_model','=','vehicle_models.id')->
select('policies.policy_number','policies.insurance_premium','policies.commission',
'policies.effective_start_date',
'policies.effective_end_date','customers.name_en',
'customers.address1','customers.address2','cities.name_en','policy_motors.policy_type',
'vehicle_makes.name_en','vehicle_models.name_en')->
where('policies.policy_number','=','DB202017036583')->first();

这个查询在我的 Mac 上完美运行。然而,当我的同事在他的 Windows 计算机上运行相同的查询时,却花了很长时间。于是他自己写了一个,那就是:

$policy = Policy::with('customer', 'motor', 'user')->
where('policy_number', 'RK202117017053')->first();

他的查询在他的 Windows 和我的 Mac 上完美运行。

问题:1. 虽然我的查询只选择所需的列,但它花费了很长时间。但他的查询采用连接表的所有列,执行速度更快。为什么会发生这种情况?

<强>2。在不同的机器上运行查询有什么区别,时间差异应该这么大?

最佳答案

  1. Although my query is selecting only required columns, it is taking forever. But his query, which takes all the columns of the joined table executes faster. Why is that happening?

即使您的查询只选择几列,它也会对表执行大量子查询,如果它们没有正确的索引,将导致长时间的执行。

他的查询速度更快,因为 laravel 执行急切加载的方式。 Laravel 不会对同一查询执行子查询,它会执行大量查询并使用集合建立关系。我的意思基本上是,您的查询运行大量内部查询,而您的合作伙伴执行多个查询,然后使用集合合并它们

  1. What difference does it make to run a query on different machines, the time difference should be that significant?

此外,如果查询在本地运行,可能会存在一些差异。通常,SQL 查询需要内存和处理器能力来进行搜索和连接,因此,如果您的 PC 由于某种原因运行速度较低,那么它将比在适当条件下的 PC 花费更多的时间。但如果 SQL 机器位于云端,那么执行上就不会有任何差异

关于mysql - Laravel 中简单查询的查询检索时间较长,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48167818/

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