0

我们的一个网站有一个表,其中包含大约 60,000 条记录。最近我们注意到页面超时,只能通过将内存限制设置为 -1 来解决。这允许页面加载,但速度很慢。此外,我不相信这是解决问题的正确方法,因为显然它表明有些事情不太正确。

我设法输出了页面正在运行的查询:

SELECT u.*,
(SELECT COUNT(*) FROM enquiry e WHERE e.user_id = u.id AND e.deleted = 0 AND e.time_started != 0) AS opened_count,
(SELECT COUNT(*) FROM enquiry e WHERE e.user_id = u.id AND e.deleted = 0 AND e.confirmed = 1 AND e.time_started != 0) AS confirmed_count,
(SELECT COUNT(*) FROM enquiry e WHERE e.user_id = u.id AND e.deleted = 0 AND e.call_back = 1 AND e.time_started != 0) AS call_back_count
FROM user u
WHERE u.active = 1 AND u.deleted = 0
ORDER BY u.username

我在 phpMyAdmin 中运行了这个查询,它需要 30 多秒才能返回结果。

我觉得查询需要以某种方式优化,但我正在努力解决如何。我猜我需要使用某种 JOIN 吗?

4

1 回答 1

7

您实际上正在运行超过 180,000 个查询,因为这 3 个子查询中的每一个都将为用户表中的每一行运行一次。

您可以尝试简化为与某些组的标准连接,例如

SELECT user.*,
    COUNT(enq.id) AS opened_count
    SUM(e.confirmed = 1) AS confirmed_count
    SUM(e.call_back = 1) AS call_back_count
FROM user
LEFT JOIN  enquiry ON enquiry.user_id = user.id
WHERE user.active = 1 and user.deleted AND enquiry.deleted = 0
GROUP BY user.id
于 2013-09-30T19:37:05.180 回答