doujianchao7446 2014-12-14 13:34
浏览 58
已采纳

在SQL Query中加入3个或更多表,获取空数组?

Ok so after going over this multiple times I don't understand what I am missing

I have at the moment 3 tables:

Users Table:

ID | Username | Password
1  |   Micky  |   123
2  |   Mouse  |   145

Questions Table:

 Question ID| Question_Title   | Question      | Rating | Category ID | User ID |
     1      | Meaning of Life? | Same as Title |  100   |      2      |    1    |
     2      | Foo is love?     | Same as Above |   95   |      4      |    2    |

Answer Table:

   Answer_ID| Answer   | Answer_Rating     | Answer_User_ID    | Question_ID |
     1      | YES      |       1           |     1             |      1      | 

And I have the following Query:

"SELECT u.username, 
q.Question_Title, 
q.Question, 
q.Rating, 
a.Answer,
a.Answer_Rating
FROM Questions q 
join Users u on u.id = q.User_ID
join Answers a on a.Question_ID = 'q.Question ID' 

WHERE q.Question_Title LIKE '%$Term%'";

This will get me the Username of the person who asked the question in addition to the Question Title, Question, Question Rating, Answer to the question and the Rating of the answer.

However what do i add to the query so that it will print out the username of the person who answered the question, via the foreign key Answer_User_ID?

No matter what I have tried, It will turn out empty, it will return the query in associative array and I am currently using print_r to display the array.

P.S: The table structure will grow and I would like to know if their is a consistent way of adding to the query to include fields and multiple foreign keys that will be added later.

  • 写回答

1条回答 默认 最新

  • dtc99987 2014-12-14 13:36
    关注

    You need another join to users:

    SELECT u.username, q.Question_Title, q.Question, q.Rating, 
           a.Answer, a.Answer_Rating,
           ua.username as AnswerUserName
    FROM Questions q join
         Users u
         on u.id = q.User_ID join
         Answers a
         on a.Question_ID = q.`Question ID` join
         Users ua
         on ua.id = a.Answer_User_ID
    WHERE q.Question_Title LIKE '%$Term%'";
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵
  • ¥15 cfx离心泵非稳态计算