The following query used to grab all comments for a particular blog article and worked well. I’ve now added a members reputation point system to my blog, similar to Stack Overflow’s reputation system, and tried modifying this query to get the reputation points from the members_reputation table, to display next to the user’s name on each comment.
I thought by adding SUM(rep.points) AS member_rep and adding a LEFT JOIN on the reputation table would do the trick but I’m getting strange results, too strange to describe. Actually, one funny behaviour is that not all the comments are being returned. Where if I removed my attempted solution, all comments are returned but I need to count/show their reputation.
Every comment has a member and every member has reputation.
SELECT comment.comment_id, comment.member_id, comment.comment,
comment.posted, member.screen_name, member.country_code, SUM(rep.points) AS member_rep
FROM blog_comments AS comment
LEFT JOIN members AS member ON comment.member_id = member.member_id
// my attempt start //
LEFT JOIN members_reputation AS rep ON comment.member_id = rep.member_id
// my attempt end //
WHERE comment.article_id = "&article_id&"
ORDER BY comment.comment_id DESC
DB Structure
comments : comment_id, member_id, comment, posted
members : member_id, screen_name, country_code
members_reputation : member_id, activity_type, points
What I want to see
This is a posted comment on my blog. Cool huh?
25/02/2012 By Martin G **850** (GBR)
If anyone can help me get back on the right road, I would be very grateful…
Here’s a couple of things I noticed.
First, your where clause is asking for comment.article_id, which you haven’t included in your table structure at the bottom of your post. I’m going to make the assumption that you just left it out, but thought I’d point it out anyways.
You can also simplify your joins by specifying USING instead of ON if the column name is the same in both tables.
Another thing to consider is the type of relationship you have between the tables. If it’s a one to one relationship than joins are simple. If it’s a one to many or many to many than joins get more complicated and you have to GROUP them together properly. I’m going to assume that each comment has only one member, and every member may have more than one rep.
Finally, you have a column that shares a name with a table alias (comment). This can lead to problems, if your sql syntax even allows it.
This is what I’d use, myself:
Also: what does the “&article_id&” represent?