Jump to content

[SOLVED] help with a query


garry

Recommended Posts

So I'm making a pretty simple blog using the codeigniter framework. Basically, in my query to get the latest 10 posts for the front page, I wanted to include the number of comments each post has.

 

My tables are as follows:

 

blog_posts

blog_comments

 

blog_comments has a field called "post_id" with the id of the corresponding post. Is there a way I can include the number of comments each post has? I'd love to get it all in one query to help with load times and such. Here's the current query I'm using to get all the post info..

 

SELECT blog_posts.id, blog_posts.user_id, blog_posts.title, blog_posts.body, blog_posts.created, blog_posts.modified, users.username AS author
FROM (blog_posts)
LEFT JOIN users ON users.id = blog_posts.user_id
ORDER BY created DESC
LIMIT 10

Link to comment
https://forums.phpfreaks.com/topic/138378-solved-help-with-a-query/
Share on other sites

Ah, I spoke too soon! This sort of does what I want, but how do I tell it to return the number of comments for each individual row returned? At the moment, I can only tell it to return the total amount of comments. Is there a mysql command that lets you do it for a particular row? Here's an example of my query:

 

SELECT `blog_posts`.`id`, `blog_posts`.`user_id`, `blog_posts`.`title`, `blog_posts`.`body`, `blog_posts`.`created`, `blog_posts`.`modified`, `users`.`username` AS author,
(SELECT COUNT(*) FROM blog_comments  WHERE ?what do i put here?) AS num_coms
FROM (`blog_posts`)
LEFT JOIN `users` ON `users`.`id` = `blog_posts`.`user_id`
ORDER BY `created` DESC
LIMIT 10

This is a stab in the dark, but try the following.

 

(SELECT COUNT(blog_comments.post_id) FROM blog_comments, blog_posts WHERE blog_comments.post_id = blog_posts.id) AS num_coms

woot, :D that was pretty much perfect, just had to remove the blog_posts table from the FROM clause and it works perfectly :)

 

(SELECT COUNT(id) FROM blog_comments WHERE blog_comments.post_id = blog_posts.id) AS num_coms

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.