我正在处理一个查询,该查询应从包含超过400,000 条记录的MyIsam表中选择定义的用户列表发送的最后 20 个帖子。唯一的问题是查询运行大约0.6秒,有时超过 2 秒。
SELECT post_id
FROM posts
WHERE post_author IN (32, 85, 222, 81, 250, [..cut..] , 5908, 4930, 6658, 6757, 6398, 6324, 6629)
ORDER BY post_id DESC
LIMIT 20
如果我删除ORDER BY查询要快得多,并且它在“post_author”列上使用正确的索引,而是执行全表扫描......进行这样的查询的最佳方法是什么?
使用 author_index 测试 #1
- 主要(post_id)
- author_index (post_author)
时间:0.7s
SELECT post_id
FROM posts
WHERE post_author IN (32, 85, 222, 81, 250, [..cut..] , 5908, 4930, 6658, 6757, 6398, 6324, 6629)
ORDER BY post_id DESC
LIMIT 20
时间:0.004s
SELECT post_id
FROM posts
WHERE post_author IN (58,68)
ORDER BY post_id DESC
LIMIT 20
使用复合索引测试 #2
- 主要(post_id)
- view_posts_index (post_id, post_author)
时间:0.05s
SELECT post_id
FROM posts
WHERE post_author IN (32, 85, 222, 81, 250, [..cut..] , 5908, 4930, 6658, 6757, 6398, 6324, 6629)
ORDER BY post_id DESC
LIMIT 20
时间:1.5s
SELECT post_id
FROM posts
WHERE post_author IN (58,68)
ORDER BY post_id DESC
LIMIT 20
使用复合索引和 author_index 测试 #3
- 主要(post_id)
- view_posts_index (post_id, post_author)
- author_index (post_author)
时间:0.7s
SELECT post_id
FROM posts
WHERE post_author IN (32, 85, 222, 81, 250, [..cut..] , 5908, 4930, 6658, 6757, 6398, 6324, 6629)
ORDER BY post_id DESC
LIMIT 20
时间:0.0037s
SELECT post_id
FROM posts
WHERE post_author IN (58,68)
ORDER BY post_id DESC
LIMIT 20
谢谢你的帮助。