mysql - 我应该使用 (select count(id) from table2) 作为 col1,还是应该在表 1 上存储一个计数器并在插入时增加它?

标签 mysql performance indexing count

我的页面似乎很慢,我有一个页面至少有 20 个“选择计数”查询,每行至少有两个字段进行计数子查询。我以为不会那么慢,但现在我不确定。我想知道在这种情况下哪一种是默认方法。 (如果我需要对某些列进行索引,我也想决定哪一列,但是 count 函数会计算某个表中的 id,所以我认为这也不是一个 inexing 问题。”

if(isset($_GET["me"])) $me="and post.memberid=".$_SESSION["memberid"]; else $me="";
$votecount="(select count(voteid) from vote where vote.postid=post.postid) as cv";
$commentcount="(select count(commentid) from comment where comment.postid=post.postid) as cc";
$countagree="(select count(voteid) from vote where vote=1 and vote.postid=post.postid) as ca";
$ismyvote=sprintf("(select vote from vote where memberid=%s and vote.postid=post.postid) as mvote",$_SESSION["memberid"]);
$plq=sprintf("select *, %s,%s,%s,%s from post where post.dateposted>=NOW() - INTERVAL %s day %s",$votecount,$commentcount,$countagree,$ismyvote,$since,$me);

当我开始开发这个时,我认为mysql会缓存主键字段的计数,并且不会导致任何问题。

最佳答案

我会尝试 Vik 的查询和 danihp 的计数器列方法。根据您的实际数据和应用,计时并比较结果。

但是,我确实相信对您最有帮助的真正答案是真正学习和使用解释计划(如果您还没有)

http://en.wikipedia.org/wiki/Explain_Plan .

您提到“似乎很慢”和“我以为不会那么慢,但现在我不确定。”并且“所以我认为这也不是索引问题。”

因此,做出更改似乎需要反复试验,除非您真正衡量更改的结果,并解释计划将对此以及索引等方面有所帮助。

祝你好运!

关于mysql - 我应该使用 (select count(id) from table2) 作为 col1,还是应该在表 1 上存储一个计数器并在插入时增加它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8080286/

相关文章:

php - LAMP #1045 - 用户 'root' @'localhost' 的访问被拒绝(使用密码 : NO))

mysql - hibernate TemporalType,日期时间列映射

mysql - 最多的电影属于哪个等级?

performance - 为什么SVG滚动性能比PNG差很多?

oracle - PL/SQL 的数值优化,或替代方案

elasticsearch - 升级到 Elastic Search NEST 7.0.1 破坏了检查索引是否存在的代码

使用索引时,Mysql Explain Query 类型为 "ALL"

MySQL:整数索引与 Varchar 索引

mysql - 从表中获取一行并将其放在查询的第一个位置

c# - 提高 IEnumerable<byte> 解析性能