简体   繁体   English

优化SQL查询

[英]Optimize SQL-query

I have following query: 我有以下查询:

Select diary_id, 
   (select count(*) 
    from `comments` as c 
    where c.d_id = d.diary_id) as diary_comments 
From `diaries` as d

It takes long time (near 0.119415 in my case). 这需要很长时间(在我的情况下接近0.119415)。 How to make it faster? 如何让它更快?

I see only one way: Doing additional query for comment number for each row from my main query. 我只看到一种方法:对主查询中的每一行的注释编号进行额外查询。 But it will be something like doing queries in cycle. 但这就像在循环中进行查询一样。 Something like: 就像是:

while ($r = mysql_fetch_array($res))
{
   $comments = mysql_query("select count(*) from `comments` where d_id = ".$r['diary_id']);
}

I think this is a bad strategy. 我认为这是一个糟糕的策略。 Any other advice? 还有其他建议吗?

SELECT d.diary_id, count(c.d_id) as diary_comments 
FROM diaries d
LEFT OUTER JOIN comments c ON (d.diary_id = c.d_id)
GROUP BY d.diary_id

I seem to have been downvoted because you can actually retreive all the data needed from just the diaries table. 我似乎被低估了,因为你实际上可以从日记表中检索所需的所有数据。 I assumed that this was a simplified example and in reality other fields from the diaries table would be required, also this method brings back records which have no comments. 我假设这是一个简化的例子,实际上需要日记表中的其他字段,这个方法也会带回没有注释的记录。 If you don't need any of these two things then I would go with the other answer. 如果你不需要这两件事中的任何一件,那么我会选择其他答案。

It looks like you have all the data you need in the comments table, so I don't see a reason for the join or subquery. 看起来您在评论表中拥有了所需的所有数据,因此我没有看到连接或子查询的原因。

SELECT d_id AS diary_id, COUNT(*) AS diary_comments
FROM `comments`
GROUP BY d_id

Definitely plus one for tomhaigh 's solution, a group by is exactly the thing in this situation. 对于tomhaigh的解决方案来说肯定是加一个,在这种情况下,一个小组就是这样。

One other option always worth remembering that you've got two choices here. 另一个选择总是值得记住,你在这里有两个选择。 Firstly to calculate the value on every read, and secondly to calculate it on every write and store the result. 首先计算每次读取的值,然后在每次写入时计算它并存储结果。 In the second case you would need an additional field on diaries called 'comments_count', this would need to be incremented on inserting a new comment. 在第二种情况下,您需要在日记上添加一个名为“comments_count”的附加字段,这需要在插入新评论时递增。 Obviously this could be less accurate than working out the count on every read and will slow your writes down. 显然,这可能不如在每次读取时计算计数并且会减慢写入速度。 But if read performance is hurting and writes are noticeably less common than reads then this can be a handy way to consider the problem. 但是如果读取性能受损并且写入明显不如读取那么常见,那么这可以是考虑问题的便捷方式。

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

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