2013-03-22 43 views
0

我知道有其他職位有像這樣,我一直在使用它們。我有三個表:PHP查詢加入得到回覆評論

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); 

回答

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

一對夫婦MySQL的事情:

  1. 如果不需要該表不加入。您不需要blog_comments表中的任何數據,因此您不應將其包含在查詢中。由於blog_reply表具有COMMENT_ID你可以只使用該表

  2. 你不需要做users_info.user_name USER_NAME的身份。這是多餘的。

  3. 您可以在WHERE子句添加到加入。

這裏是我會寫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 

我希望幫助!

+0

是感謝幫助。是的,你說得對不需要的表,我認爲這是從試圖獲得在同一時間評論及回覆遺留下來的。 – hobbywebsite 2013-03-22 21:11:24