简体   繁体   English

在PHP查询中难以连接3个表

[英]Difficulty with join 3 tables in a query in php

My database has 3 tables i wish to access in the select query but I cannot seem to get it to work. 我的数据库有3个表,我希望在select查询中访问这些表,但似乎无法正常工作。 Selecting from 2 tables works fine so I know everything else is working apart from my code for selecting from 3 tables. 从2个表中进行选择可以很好地工作,所以我知道除了从3个表中进行选择的代码以外,其他所有功能都在起作用。 My database has been created on PHPmyadmin 我的数据库已在PHPmyadmin上创建

The Tables are as follows: 表格如下:

forum_replies forum_replies

  • reply_id reply_id
  • topic_id topic_id
  • user_id 用户身份
  • reply_text REPLY_TEXT
  • reply date 回复日期

forum_topics forum_topics

  • topic_id topic_id
  • category_id CATEGORY_ID
  • user_id 用户身份
  • topic_title 主题标题
  • topic_description topic_description
  • topic_date topic_date

users 用户

  • user_id 用户身份
  • username 用户名

This is the code I have tried to use and shows the fields I wish to 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); 

Example in code would be appreciated. 代码示例。 Thanks 谢谢

You miss the , after users.username .. 你错过了,以后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

Use this query: 使用此查询:

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

Apart from syntax errors, you should use LEFT JOIN and table alias in your case. 除语法错误外,您还应使用LEFT JOIN和表别名。


To show also the topic creator's username, you can adjust the query to the following: 要同时显示主题创建者的用户名,您可以将查询调整为以下内容:

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

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

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