PHP查询加入以获得评论回复

时间:2013-03-22 20:58:32

标签: php mysql join comments

我知道还有其他帖子,我一直在使用它们。我有三张桌子:

users_info
  user_id | user_name

blog_comments
  comment_id | comment

blog_reply
  user_id | comment_id | reply | reply_date

我尝试加入表以从users_info获取user_name并通过blog_comments.comment_id返回blog_reply

我一直在使用: mysql structure for comments and comment replies

我被困在桌子上,非常感谢任何帮助。

    $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 个答案:

答案 0 :(得分:1)

一些MySQL的东西:

  1. 如果您不需要表格,请不要加入。您不需要blog_comments表中的任何数据,因此您不应将其包含在查询中。由于blog_reply表具有comment_id,因此您只需使用该表

  2. 您不需要执行users_info.user_name AS user_name。这是多余的。

  3. 您可以将where子句添加到连接中。

  4. 以下是我将如何编写MySQL语句:

    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
    

    我希望有所帮助!

答案 1 :(得分:0)

这应该有效:

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