我有一个系统,其中商店是一个帐户,客户在这些商店购物。有一张表存储客户和商店的多对多关联。该表的关键属性是 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/