我有两个数据库表,我试图让它们一起工作。他们被称为用户和 forun_topics
在 forum_topics 中,我有一个名为 topic_creator 的专栏。这将始终是一个整数。
在用户中我有一个名为 id 的列。
users 表中的 id 就是 topic_creator 整数。
所以我想要完成的是将 topic_creator 与用户表中的 id 相关联,然后用它找到我的用户表中名为用户名的另一列。
因此,为了使这变得非常简单,我尝试输出发帖人的用户名。
到目前为止,这是我的查询,它显示了 topic_creator,我可以弄清楚如何在 SQL 运行后输出所有内容,但我不知道如何向该查询添加另一个数据库表,然后找到用户名字段。我最大的问题是如何在之后获取用户名字段。
$query2 = mysqli_query($con,"SELECT t.*, c.id AS cid FROM forum_topics AS t, forum_categories AS c ORDER BY topic_reply_date DESC LIMIT 3")
我该怎么做?
更新以显示更多代码
$query2 = mysqli_query($con,"SELECT t.*, c.id AS cid
FROM forum_topics AS t
INNER JOIN forum_categories AS c
on t.categories.ID = c.ID
INNER JOIN users u
on u.id = t.topic_creator
ORDER BY topic_reply_date DESC LIMIT 3")
or die ("Query2 failed: %s\n".($query2->error));
$numrows2 = mysqli_num_rows($query2);
if($numrows2 > 0){
$topics .= "<table class='top_posts_table'>";
//Change link once discussion page is made
$topics .= "<tr><th class='top_posts_th'>Topic Title</th><th class='top_posts_th'>Replies</th><th class='top_posts_th'>Views</th></tr>";
$topics .= "<tr><td colspan='3'><hr /></td></tr>";
while($row2 = mysqli_fetch_assoc($query2)){
$cid = $row2['cid'];
$tid = $row2['id'];
$title = $row2['topic_title'];
$views = $row2['topic_views'];
$date = $row2['topic_date'];
$date = fixDate($date);
$creator = $row2['username'];
$topics .= "<tr><td class='top_posts_td'><a href='forum_view_topic.php?cid=".$cid."&tid=".$tid."'>".$title."</a><br /><span class='post_info'>Posted
by: ".$creator."<br> on ".$date."</span></td><td class='top_posts_td'>0</td><td align='center'>".$views."</td></tr>";
$topics .= "<tr><td colspan='3'><hr /></td></tr>";
}
最佳答案
类似...但不知道 form_topics 与 forum_categories 的关系,这可能是错误的。
它还假设您只希望记录出现在所有 3 个表中,并且当不存在匹配项时,记录将被排除。
SELECT t.*, c.id AS cid, u.*
FROM forum_topics AS t
INNER JOIN forum_categories AS c
ON t.category_id = c.id
INNER JOIN users u
on u.id = t.topic_Creator
ORDER BY topic_reply_date DESC LIMIT 3
您当前的方法是在 forum_topics 和 forum_categories 之间进行交叉连接。这不太可能是您真正想要的。
关于php - 在两个表之间使用 id 来输出想要的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31922649/