简体   繁体   English

在这两个表中查询性能更好?

[英]Better performance in this two table query?

I am trying to retrieve the id's of the blogs from the users that sessionid follow: 我正在尝试从sessionid遵循的用户那里检索博客的ID:

SELECT * FROM articles
 WHERE id_usuario IN (SELECT toid FROM follows WHERE fromid = '$id')

This gives me the expected result but the performance is pretty bad even with a small number of rows. 这给了我预期的结果,但是即使行数很少,性能也很差。

Would I be better served with a join? 加入我会更好吗?

You can quickly fix this by rewriting as: 您可以通过重写为以下内容来快速解决此问题:

SELECT * FROM articles WHERE id_usuario IN (SELECT toid FROM follows WHERE fromid = '$id' AND id_usuario = toid)

With your query, MySQL will try and materialize the outer query first (select all articles) and then filter based on the inner query, which is not efficient, unfortunately it's not smart enough right now to realise it should turn that subquery into a join. 对于您的查询,MySQL将首先尝试实现外部查询(选择所有文章),然后基于内部查询进行过滤,这效率不高,不幸的是,它现在还不够聪明,以至于无法意识到应该将子查询转换为联接。

You can give the optimizer the hint it needs though by referencing the outer table from the inner table on the condition you want to filter by, as I've done above. 您可以通过上面要过滤的条件从内部表中引用外部表,从而为优化器提供所需的提示,如上所述。

Even for a simple query like that, it would be very surprising if a join offered better performance. 即使对于这样的简单查询,如果联接提供了更好的性能,也将非常令人惊讶。

The one thing I can suggest is an index on id_usuario . 我可以建议的一件事是id_usuario上的索引。

Also, to analyse what the engine does with your query, use Explain . 另外,要分析引擎对查询的作用,请使用Explain

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM