I’m relatively new to MySQL and I am stumped with this section.
I am building a simple blog page which will display a blog along with the comments associated with it. I currently have two tables to handle this data:
Blogs
.blog_id (primary), .blog_title, .blog_date, .blog_post
Comments
.comment_id (primary), .blog_id, .comment_name, .comment
What I am trying to do is pull a specific blog which matches an ID and pull the comments tied to that blog. Here is my query:
SELECT * FROM blogs JOIN comments ON blogs.blog_id=comments.blog_id WHERE blogs.blog_id = $active ORDER BY comments.comment_id
This query results in pulling the correct information but if there are two comments on the blog, it will display the blog and everything twice as it’s looping through the comments. I want to display all the blog information once and then have it loop through the comments.
I hope I explained this clearly. Any help would be fantastic. Thank you.
The behavior you are describing is what a join is supposed to do. If you only want 1 record for each of the blog entries, then you need to use group by. To get a list of all the blogs records with the number of comments you can do a query like:
However, you said you wanted to display just the blog, and then the comments associated with that blog. In that case you would most likely just use an initial query to pull all the blogs, and then another query as you loop through all the blog entries to get the comments for each blog. Here is some pseudocode.
You could just do a single select for all the comments, which would be more efficient, but makes the resulting code more complex as you have to find the records using php in the resulting list. It’s mush simpler to just use multiple queries, and for most blogs (10 articles on a page, max) it won’t make much of a difference. If you really want to use a single query, you can structure your program as in the pseudocode below.