Below is a location table
CREATE TABLE locations (
`id` int(11),
`user_id` int(11),
`timestamp` datetime
PRIMARY KEY (`id`),
KEY `index_on_timestamp` (`timestamp`),
KEY `index_on_user_id` (`user_id`)
);
我运行以下查询来检索给定用户过去一周的位置:
SELECT * FROM locations
WHERE user_id=20
AND timestamp > NOW() - INTERVAL 7 DAY;
我们在 user_id 和时间戳上都有索引,但是,这个查询需要相当长的时间来运行。需要帮助解决这个问题。
最佳答案
您希望按顺序对用户 ID 和时间戳建立索引:
create index user_locations_user_id_timestamp on user_locations(user_id, timestamp)
这将完全满足 where
子句。
关于mysql - 提高sql查询性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22548789/