简体   繁体   中英

joining a count on a query

I have 2 tables: comments & blog

blog has the following fields: id(Unique key),title, author, body, date, img, imgdes, tags

comments : key(Unique key), postid(related to the id of blog),name, email, date, message

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"

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"

The comments a and blog c don't seem to be correct references.

Should it be 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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