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%'";
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 MATLAB APP 制作出现问题
  • ¥15 wannier复现图像时berry曲率极值点与高对称点严重偏移
  • ¥15 利用决策森林为什么会出现这样·的问题(关键词-情感分析)
  • ¥15 DispatcherServlet.noHandlerFound No mapping found for HTTP request with URI[/untitled30_war_e
  • ¥15 使用deepspeed训练,发现想要训练的参数没有梯度
  • ¥15 寻找一块做为智能割草机的驱动板(标签-stm32|关键词-m3)
  • ¥15 信息管理系统的查找和排序
  • ¥15 基于STM32,电机驱动模块为L298N,四路运放电磁传感器,三轮智能小车电磁组电磁循迹(两个电机,一个万向轮),怎么用读取的电磁传感器信号表示小车所在的位置
  • ¥15 如何解决y_true和y_predict数据类型不匹配的问题(相关搜索:机器学习)
  • ¥15 PB中矩阵文本型数据的总计问题。