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 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码