0

我正在处理一个查询,该查询应从包含超过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

谢谢你的帮助。

4

3 回答 3

1

在 post_author 和 post_id 列上创建索引:

CREATE INDEX ix_post_search ON posts(post_author, post_id);

这将允许 MySQL 通过仅​​查看此索引来满足整个查询。

于 2012-08-28T20:13:04.477 回答
0

Make sure your query uses an index on the post_id (and probably on post_author, but that's not part of your question), otherwise in your case a whole range scan will be started and stopped as soon as the required amount of rows are generated.

于 2012-08-28T19:36:51.560 回答
0

我想我会尝试这样做,确保在列作者上有一个索引,并且在唯一 ID 上自然也有一个索引:)

SELECT p2.post_id FROM posts p2
WHERE p2.post_id IN (
  SELECT p1.post_id
  FROM posts p1
  WHERE p1.post_author IN (32, 85, 222, 81, 250,  [..cut..] , 5908, 4930, 6658, 6757, 6398, 6324, 6629)
 )
ORDER BY p2.post_id
LIMIT 20

让我知道它是否能解决您的问题

于 2012-08-28T19:45:20.260 回答