【发布时间】:2017-01-03 05:54:41
【问题描述】:
我有一个表 user_notifications 有 1100000 条记录,我必须在下面运行这个查询,但是完成查询需要 3 分钟以上我可以做些什么来改善获取时间。
SELECT `user_notifications`.`user_id`
FROM `user_notifications`
WHERE `user_notifications`.`notification_template_id` = 175
AND (DATE(sent_at) >= DATE_SUB(CURDATE(), INTERVAL 4 day))
AND `user_notifications`.`user_id` IN (
1203, 1282, 1499, 2244, 2575, 2697, 2828, 2900, 3085, 3989,
5264, 5314, 5368, 5452, 5603, 6133, 6498..
)
IN 块中的用户 ID 有时高达 1k。
为了优化,我在user_notification 表中的user_id 和notification_template_id 列上建立了索引。
【问题讨论】:
-
比较 1000
user_id1+ 百万条记录的值需要一些时间,即使 MySQL 正在使用你想要的索引。 “年龄”有多长? -
@TimBiegeleisen 平均 2-5 分钟
-
您是在 user_id 和 notification_template_id 上创建了单独的索引,还是为两者创建了一个?试试后者。
-
@wumpz 单独索引。请看我附上的截图。如何为两者创建一个?
-
create index my_compound_index on user_notifications(user_id, notification_template_id)
标签: mysql sql query-performance