mysql查询性能太低,我该怎样才能改进它

时间:2014-10-06 12:48:09

标签: mysql

我有3个表,用户,user_to_topics,主题。

SELECT
topics.* FROM
user_to_topics INNER JOIN topics
ON topics.id = user_to_topics.topic_id
WHERE user_to_topics.user_id=12345
ORDER BY topics.created_at DESC
LIMIT 10

主题表有5M记录,user_to_topics有10M,这个sql意味着找到感兴趣的id为12345的用户的所有主题,按created_at DESC命令

当我这样查询时

SELECT topic_id FROM user_to_topics WHERE user_id = 12345

然后

SELECT * FROM topics WHERE id IN (the results above) ORDER BY created_at DESC LIMIT 10

它也很慢

我上面使用的所有列都添加了单列索引

我应该如何为这些表添加索引,还是应该更改这些表的结构?

3 个答案:

答案 0 :(得分:0)

在查询之前使用EXPLAIN,然后查看哪些列应该被编入索引,通常是那些使用更多的列,我已经使用索引将我的AJAX请求时间从1.6分钟减少到7秒

答案 1 :(得分:0)

在select query中使用column_name而不是*。

使用*获取表中的所有列,可能会降低查询速度。

使用您想要执行查询所需的列名称。

答案 2 :(得分:0)

尝试使用下面的查询,我认为您的查询结构可能是花费时间的原因

Select * From db.topics, db.users, db.user_to_topics
where topics.id = user_to_topics.topic_id
and user_id = '12345'
order by topics DESC
limit 10;

这应该运行得更快