php - MySQL 查询内存不足

标签 php mysql laravel

我有一个系统,其中商店是一个帐户,客户在这些商店购物。有一张表存储客户和商店的多对多关联。该表的关键属性是 accountid、customerid 和 last_visit_date。对于一组 accountid,我需要找到每个客户的最近一次访问。我有一个查询可以完美运行但似乎效率低下,因为它用完了大约 21000 个客户的内存。

SELECT ac.customerId FROM account_customer ac 
      INNER JOIN (SELECT customerId, max(last_visit_date) AS 
                     LastVisitDate FROM account_customer 
                  WHERE accountId in        
                     (311,307,318,320,321,322,323,332,347,439,519,630,634,643) 
                 GROUP BY customerId) grouped_ac 
     ON ac.customerId = grouped_ac.customerId 
          AND ac.last_visit_date = grouped_ac.LastVisitDate 
          AND ac.last_visit_date <= '2016-10-18' 
          OR ac.last_visit_date is null

当我运行上述查询时,它为较小的数据集提供了正确的结果,但对于较大的数据集,我得到了内存错误。我什至不是在谈论一个非常大的群体 - 大约 20,000 多个客户。

如有任何帮助,我们将不胜感激。

最佳答案

你可能是说

ac.customerId = grouped_ac.customerId 
AND ac.last_visit_date = grouped_ac.LastVisitDate 
and (ac.last_visit_date <= '2016-10-18' or ac.last_visit_date is null)

我认为如果没有括号,查询可能会返回 last_visit_date 为空的所有记录。

看看 How exactly does using OR in a MySQL statement differ with/without parentheses? 的答案.

关于php - MySQL 查询内存不足,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40640328/

相关文章:

php - 如何按一列排序,然后将同一列 ID 的最新 block 推到顶部?

mysql - Eloquent删除与MySQL外键级联

php - 从具有年份总记录的表中获取按月数据

mysql - 创建一个子查询别名以在 Laravel 查询生成器中使用它

PHP GD 静默失败

mysql - 如何查看 RDS 数据库中存储了哪些数据?

mysql - 内存优化的 powershell Out-File - 为大文件编码没有 BOM 的 utf8

mysql - 构建一个 WordPress 查询以按类别以及 meta_key 的数字范围选择帖子

php - 在 PHP 中合并类成员

php - 您如何计算 PHP 中的服务器负载?