0

I know that there are other posts out there like this, I've been using them. I've got three tables:

users_info
  user_id | user_name

blog_comments
  comment_id | comment

blog_reply
  user_id | comment_id | reply | reply_date

I'm trying to join the tables to get user_name from users_info and to return blog_reply by blog_comments.comment_id

I've been using: mysql structure for comments and comment replies

I'm stuck on the table joins, any help is much appreciated.

    $get_replies = ("SELECT
                      blog_reply.user_id,
                      blog_reply.comment_id,
                      blog_reply.reply,
                      blog_reply.reply_date,
                      users_info.user_name AS user_name
                    FROM blog_reply
                    JOIN users_info ON blog_reply.user_id = users_info.user_id
                    LEFT JOIN blog_comments ON blog_reply.comment_id = blog_reply.comment_id
                    JOIN users_info ON blog_reply.user_id = users_info.user_id
                    WHERE blog_comments.comment_id = '{$comment_id}'
                    ORDER BY blog_reply.reply_date DESC");

    $reply = mysql_query($get_replies);

2 Answers 2

1

A couple MySQL things:

  1. If you don't need the table don't join it. You don't need any data out of the blog_comments table so you shouldn't include it in your query. Since the blog_reply table has the comment_id you can just use that table

  2. You don't need to do users_info.user_name AS user_name. That's redundant.

  3. You can add the where clause to the join.

Here is how I would write the MySQL statement:

SELECT
    blog_reply.user_id,
    blog_reply.comment_id,
    blog_reply.reply,
    blog_reply.reply_date,
    users_info.user_name
FROM 
    blog_reply
JOIN 
    users_info 
ON 
    blog_reply.user_id = users_info.user_id AND
    blog_reply.comment_id = '{$comment_id}'
ORDER BY 
    blog_reply.reply_date DESC

I hope that helps!

Sign up to request clarification or add additional context in comments.

1 Comment

yes thanks that helps. Yeah you're right about that not needed table, I think it's left over from trying to get comments and replies at the same time.
0

This should work:

FROM blog_reply
JOIN users_info ON blog_reply.user_id = users_info.user_id
JOIN blog_comments ON blog_reply.comment_id = blog_comments.comment_id
WHERE blog_comments.comment_id = '{$comment_id}'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.