I am developping a site where users can post comments and each comment is categorized. I have a page where users can go and see a list of all the categories on the site with the latest 5 comments posted in them.
The information I need to retrieve from the database is:
- A list of categories
- 5 comments in each categories
This is what I have right now (simplified to basic PHP):
echo "<ul>";
$query = mysql_query("SELECT * FROM categories");
while($result = mysql_fetch_assoc($query)){
echo "<li><h2>{$result['category_name']}</h2>";
$query_comments = mysql_query(
"SELECT * FROM comments WHERE ".
"category_id = '{$result['id']}' ".
"ORDER BY created_at DESC LIMIT 5");
while($result_comments = mysql_fetch_assoc($query_comments)){
echo "{$result_comments['username']} wrote {$result_comments['text']} on {$result_comments['created_at']}<br>";
}
echo "</li>";
}
echo "</ul>";
It would look like this (assuming my categories are Fruits name)
Apple Jay wrote blah blah blah - August 5, 2009 Bob wrote hello hello hello - August 5, 2009 Tom wrote super super - August 5, 2009 Edward wrote no no no - August 5, 2009 Kaysie wrote super no! - August 5, 2009 Orange Cassie wrote ye ye ye ye - August 5, 2009 Alfonce wrote whoohoo - August 5, 2009 Arthur wrote love oranges - August 5, 2009 Alice wrote yes yes yes - August 5, 2009 Xavier wrote Lorem ipsum dolor sit amet - August 5, 2009 Strawberry Chris wrote Lorem ipsum dolor sit amet - August 5, 2009 Hubert wrote Lorem ipsum dolor sit amet - August 5, 2009 Martin wrote Lorem ipsum dolor sit amet - August 5, 2009 Lyon wrote Lorem ipsum dolor sit amet - August 5, 2009 Paris wrote Lorem ipsum dolor sit amet - August 5, 2009 Blueberry etc...
The problem is, if there are a lot of categories, I will have performance issues, especially if there are a lot of users using the site.
I am struggling to find way to reduce the amount of queries needed. Does anyone has an idea of how I could do that ?
UPDATE I tried to LEFT JOIN the category table with the comments table however, I didn't find a way to limit the amount of comments per category because if I use LIMIT 5, it only limits the amoutn of comments returned.