改善sql查询性能

拉古
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和timestamp上都有索引,但是,此查询需要相当长的时间才能运行。需要帮助解决此问题。

戈登·利诺夫

您需要按此顺序在用户ID和时间戳建立索引

create index user_locations_user_id_timestamp on user_locations(user_id, timestamp)

这将完全满足该where条款。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章