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
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

Link to comment
Share on other sites

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

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.