加入没有价值的 Table

Joining Table that has no value

我正在为另一个开发人员构建的客户端开发一个友谊站点。客户在问题 table 中添加了新问题。我想不出一个查询会 return 所有问题的结果,即使对于没有回答新问题的老用户也是如此。

问题是老用户在 用户问题 table 中没有条目,所以我怎样才能为老用户获得默认值 'not answer'谁没有在 用户问题 table?

中输入值

请参阅下面的 table 结构

用户Table

id | username
0  | louis

用户问题Table

ID | USERID | Question ID | Answer ID
0  | 1      | 0           | 5
1  | 1      | 1           | 8

问题Table

ID | QUESTION                    
0  | What is your favorite color 
1  | What is your gender         
2  | What is your favorite t.v. show        

回答Table

ID | answer
5  | Blue
8  | female

这是我想要的结果:

user       | question                        | answer
louis      | What is your favorite color     | blue
louis      | What is your gender             | female
louis      | What is your height             | Not Answered

您想使用 cross join 来获取所有用户和所有问题的组合。然后使用 left join 引入有关现有答案的信息。最后一块是coalesce()在没有答案的时候代入一个值:

select u.username, q.question, coalesce(a.answer, 'Not Answered')
from user u cross join
     question q left join
     userquestion uq
     on uq.userid = u.id and
        uq.questionid = q.id left join
     answer a
     on uq.answerid = a.id

我会得到所有问题,留下答案和用户问题,并与用户进行交叉连接:

select 
    username, 
    question, 
    answer = isnull(answer,'Not Answered')
from Question q
cross join User u 
left join UserQuestion uq on uq.QuestionID = q.ID and u.id = uq.USERID
left join Answer a on uq.AnswerID = a.ID

Sample SQL Fiddle