繁体   English   中英

在两个表之间使用ID来输出所需数据

[英]Using id's between two tables to output wanted data

我有两个数据库表,我试图一起工作。 它们被称为用户和forun_topics

在forum_topics中,我有一列称为topic_creator。 这将始终是整数。

在用户中,我有一列称为id。

用户表中的ID是topic_creator整数。

因此,我要完成的工作是将topic_creator与users表中的id关联,然后与该表找到我在users表中拥有的另一列称为username。

因此,为了使其变得非常简单,我尝试输出发帖人员的用户名。

到目前为止,这是我的查询,其中显示有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之间进行交叉联接。 这不太可能是您真正想要的。

我不确定您的SQL级别是什么,但这通常是基本级别。 我建议在继续您的项目之前,先停下来再阅读一遍,至少要对这个主题有一个基本的了解。 这是最常见的操作之一,并且掌握它的工作原理总是比StackOverflow上的一些答案要好,尤其是因为这很可能会引起很多麻烦。

您正在寻找的是这样的:

SELECT * FROM forum_topics
INNER JOIN users
ON forum_topics.topic_creator = users.id
ORDER BY forum_topics.topic_reply_date DESC
LIMIT 3

这可以通过多种方式进行改进,例如为表名提供别名并指定所需的实际列(我在其中留下了*)。

如果可以,请尝试与命名保持一致。 在您的示例中,“ topic_creator”可能会变成“ user_id”,在这种情况下这是正常的。 通常,在两个表之间具有1:N关系的情况下,请尝试将外键命名为“ user_id”(与users.id关联),“ topic_id”(topics.id)等。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM