我需要为每一篇博客文章获取评论的数量,并且我目前使用的是这个SQL。
select
id as article_id,
title,
content,
pic,
(select count(id) as comments from article_comments where
article_comments.article_parent_id = article_id group by article_id) as comments
from articles limit 1000);与没有计数(Id)子查询的查询相比,该查询有一些显著的延迟。对于1000篇精选的文章,延迟大约2-4秒。是否有提高此查询性能的方法?
发布于 2014-06-28 16:34:18
对大数据使用计数会造成越来越多的延迟。为了提高文章中注释的数量,在项目表中创建一个名为comment_count的属性。每当有人输入评论时,在相应的文章记录中,这个数字就会增加1。这样,当您想检索文章时,不必每次加载页面时都要计算注释,它只是一个属性。
发布于 2014-06-28 17:02:40
这是您的查询:
select id as article_id, title, content, pic,
(select count(id) as comments
from article_comments
where article_comments.article_parent_id = articles.article_id
group by article_id
) as comments
from articles
limit 1000;首先,group by是不必要的。第二,索引article_comments(article_parent_id)应该会有所帮助。最后的查询可能如下所示:
select a.id as article_id, a.title, a.content, a.pic,
(select count(*) as comments
from article_comments ac
where ac.article_parent_id = a.article_id
) as comments
from articles a
limit 1000;请注意,这还引入了表别名。这使得查询更易于编写和读取。
发布于 2014-07-03 10:56:04
我发现,如果情况允许,那么进行第一个sql查询,然后从其中提取所需的in,并使用in()操作符进行第二个sql查询,而不是连接表/嵌套查询,速度要快得多。
select id as article_id, title, content, pic from articles limit 1000此时,我们需要声明字符串变量,该变量将包含将在下一个查询中进入()操作符中的一组is。
<?php $in = '1, 2, 3, 4,...,1000'; ?>现在,我们为一组以前获取的文章ids选择注释计数。
select count(*) from article_comments where article_id in ($in)这个方法在php代码方面略显混乱,因为在他看来,我们需要包含文章数据的$articles数组和包含每一篇文章的注释计数的$ comments‘制品_id’数组。
与性能上的改进相反,该方法对于php代码比较混乱,因此不可能在第二个表或任何下一个表中搜索值。因此,只有在性能是关键且不需要其他操作的情况下,此方法才适用。
https://stackoverflow.com/questions/24468806
复制相似问题