在 php 的查询中连接 3 个表有困难

Difficulty with join 3 tables in a query in php

我的数据库有 3 个表,我希望在 select 查询中访问,但我似乎无法让它工作。从 2 个表中进行选择工作正常,所以我知道除了我从 3 个表中 selecting 的代码外,其他一切都在工作。我的数据库已在 PHPmyadmin

上创建

表格如下:

forum_replies

forum_topics

用户

这是我尝试使用的代码,显示了我希望使用的字段 select:

    $queryreply = "SELECT forum_replies.reply_id, forum_replies.topic_id, forum_replies.user_id,
                       forum_replies.reply_text, forum_replies.reply_date, users.user_id, users.username
                       forum_topics.topic_id,forum_topics.topic_title, forum_topics.topic_date
                       FROM forum_replies
                       JOIN forum_topics
                       ON forum_replies.topic_id = forum_topics.topic_id
                       JOIN users
                       ON forum_replies.user_id = users.user_id

                       ";


        $result = mysql_query($queryreply) or die (mysql_error());
        $row = mysql_fetch_array($result); 

代码中的示例将不胜感激。谢谢

您错过了 users.username 之后的 ,..

SELECT forum_replies.reply_id, forum_replies.topic_id, forum_replies.user_id,
forum_replies.reply_text, forum_replies.reply_date, users.user_id, users.username,
 forum_topics.topic_id,forum_topics.topic_title, forum_topics.topic_date

使用这个查询:

SELECT a.reply_text, a.reply_date, b.topic_title, c.username
FROM forum_replies a
LEFT JOIN forum_topics b ON a.topic_id=b.topic_id
LEFT JOIN users c ON a.user_id=c.user_id
// apply WHERE, ORDER, GROUP if needed

除了语法错误,您还应该使用 LEFT JOIN 和 table 别名。


要同时显示主题创建者的用户名,您可以将查询调整为以下内容:

SELECT a.reply_text, a.reply_date, b.topic_title, c.username AS reply_user, (SELECT username FROM users WHERE user_id=b.user_id) AS topic_creator
FROM forum_replies a
LEFT JOIN forum_topics b ON a.topic_id=b.topic_id
LEFT JOIN users c ON a.user_id=c.user_id
// apply WHERE, ORDER, GROUP if needed