【发布时间】:2012-08-23 08:58:13
【问题描述】:
我正在处理一个查询,该查询应从包含超过 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
- PRIMARY(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
- PRIMARY(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
- PRIMARY(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
感谢您的帮助。
【问题讨论】:
-
你有post_author的索引吗?
-
你的 post_id 列是那个表的索引吗?如果不是,则应将其设置为主键。
-
尝试创建复合索引
(post_author, post_id)。 -
如果表是MyISAM,试试(倒序)复合索引:
(post_id, post_author) -
看起来没有办法使用具有范围条件和顺序的多重索引......任何解决方案?我已经发布了所有建议的索引和相关查询:(
标签: mysql performance sql-order-by where-in