我有以下MySQL查询。
SELECT user_id
SUM(reached = 'Y') AS reached_count,
SUM(reached = 'N') AS not_reached_count
FROM goals
GROUP BY user_id
在表目标中,我大约有200万个条目。该查询大约需要45秒才能执行。
最重要的部分似乎是
SUM(reached = 'Y')
,它花费了很长时间。我将它与COUNT(*)
进行了比较,后者确实要快得多,但不能区分Y和N。编辑:
reached
的类型是ENUM('Y','N')
最佳答案
尝试在user_id, reached
上添加索引,然后尝试查询:
SELECT user_id, reached, count(*)
FROM goals
GROUP BY user_id, reached