【问题标题】:Laravel querying from MySQL table containing more than 150k recordsLaravel 从包含超过 15 万条记录的 MySQL 表中查询
【发布时间】:2022-10-02 18:52:07
【问题描述】:

我有一个有 27 列的表,包含超过 150k 行。

当我试图获取查询的计数时,选择 Population 是 900 行,并且收件人表包含超过 150k 行。

所以我必须为所有 900 行重复所有 150k。

$pops=Population::all();
foreach ($pops as $pop){     
$pop[\"count\"]=
                Recipient::where(\'population_id\',$pop->id)
                ->whereIn(\"recipients.employment_condition\",[0,1,3])
                ->where(\"recipients.has_car\",\"!=\",0)
                ->where(\"recipients.has_land\",\"!=\",0)
                ->count();
}

这就是让服务器等待大约 45 秒并给我一个内部服务器错误的原因 - 如何优化这样的东西?

笔记:我已经将 4 个 Recipient 列作为没有好的经验的索引!

  • 请附上表格和索引定义
  • 并提供生成的 SQL。

标签: mysql laravel


【解决方案1】:

对于标准 SQL,这是非常简单的查询,而且是一个,而不是 900 个单独的循环查询。

select p.id, count(r.population_id) from population p
left join recipients r on (p.id = r.population_id
  and r.employment_condition in (0,1,3)
  and r.has_car !=0
  and r.has_land !=0
)
group by p.id

甚至更好

select p.*, ifnull(counter,0) from population p
left join 
  (select 
      r.population_id, 
      count(*) counter 
   from recipients r 
   where 
     r.employment_condition in (0,1,3)
     and r.has_car !=0
     and r.has_land !=0
   group by r.population_id
) c on (c.population_id = p.id)

并将其作为原始查询执行。

DB Fiddle example

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-09
    • 2013-11-02
    • 1970-01-01
    • 2021-12-21
    相关资源
    最近更新 更多