简体   繁体   English

加入查询计数

[英]joining a count on a query

I have 2 tables: comments & blog 我有2个表:评论和博客

blog has the following fields: id(Unique key),title, author, body, date, img, imgdes, tags 博客有以下字段:id(唯一键),标题,作者,正文,日期,img,imgdes,标签

comments : key(Unique key), postid(related to the id of blog),name, email, date, message 评论:密钥(唯一密钥),postid(与博客的ID相关),名称,电子邮件,日期,消息

Im trying to display all of my blog post and the number of comments on every post. 我试图显示我的所有博客文章和每篇文章的评论数量。

So im trying to "count(postid) where postid=id" 所以我试图“计数(postid)postid = id”

I got something to work but its based around having 1 comment which wont work but this is it: 我有一些工作,但它的基础上有一条评论不会工作,但这是它:

 SELECT a.postid,c.author,c.title, c.id,c.body,c.date,c.pic, c.tags, c.imgdesc,  
 COUNT(*) AS num_comments FROM comments a LEFT JOIN blog c ON c.id = a.postid 
 GROUP BY c.id order by id DESC"

Again this only work when everything has a comment and i get why but i cant figure out how to implement what I want. 再一次,只有当所有内容都有评论并且我明白为什么但是我无法弄清楚如何实现我想要的东西时才能工作。

To put it all out there i have: 把它全部放在那里我有:

 $sql="***( help 1 of 2) what to set the query to****"
 $query = mysql_query($sql) or die(mysql_error());
  <?php do{ ?>
  <html stuff here>
  <?php echo $blog['title']?><br>
  <?php echo $blog['*******(help 2 of 2) # of comments display here******']
  <?php } while($blog = mysql_fetch_assoc($sql));?>

im sure this is a easy join but i have no clue thanks! 我确定这是一个简单的加入,但我不知道谢谢!

使用此查询它可能适合您

SELECT a.postid,c.author,c.title, c.id,c.body,c.date,c.pic, c.tags, c.imgdesc, COUNT(a.key) AS num_comments FROM blog c left outer join comments a ON a.postid = c.id GROUP BY c.id order by id DESC

如果你想要所有博客文章,那么它应该在左连接的左侧。

I think the issue lies where you write: FROM comments a LEFT JOIN blog c ON c.id = a.postid GROUP BY c.id order by id DESC" 我认为问题出在你写的地方: FROM comments a LEFT JOIN blog c ON c.id = a.postid GROUP BY c.id order by id DESC"

The comments a and blog c don't seem to be correct references. comments ablog c似乎不是正确的参考。

Should it be FROM comments.a LEFT JOIN blog.c ON ...? 应该是FROM comments.a LEFT JOIN blog.c ON ...?

Are you trying to count the number of comments in each blog? 您是否想要计算每个博客中的评论数量? if yes then, SELECT c.postid,count(key) as num_of_comments FROM blog b, comments c WHERE b.id = c.postid GROUP BY c.postid 如果是,则SELECT c.postid,count(key) as num_of_comments FROM blog b, comments c WHERE b.id = c.postid GROUP BY c.postid

Another easy way out: As you have the postid as a foreign key, you can just get the results from comments table SELECT postid,count(key) as num_of_comments FROM comments GROUP BY postid 另一个简单的方法:由于你将postid作为外键,你可以从注释表中获得结果SELECT postid,count(key) as num_of_comments FROM comments GROUP BY postid

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

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