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

时间:2014-12-14 13:34:37

标签: php mysql database codeigniter syntax

好的,经过这次多次,我不明白我错过了什么

我目前有3张桌子:

用户表:

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

问题表:

 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_ID| Answer   | Answer_Rating     | Answer_User_ID    | Question_ID |
     1      | YES      |       1           |     1             |      1      | 

我有以下查询:

"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%'";

除了问题标题,问题,问题评分,问题答案和答案评分之外,这还会给我一个提问题的人的用户名。

但是,我将如何添加到查询中,以便通过外键Answer_User_ID打印出回答问题的人的用户名?

无论我尝试过什么,它都会变空,它将返回关联数组中的查询,我目前正在使用print_r来显示数组。

P.S:表结构将会增长,我想知道它们是否是添加到查询中的一致方式,以包含将在以后添加的字段和多个外键。

1 个答案:

答案 0 :(得分:0)

您需要另一个joinusers

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%'";