加入没有价值的表格

时间:2015-03-16 01:11:00

标签: sql database join unique

我正在为另一位开发人员构建的客户的友情网站工作。客户在问题表中添加了新问题。我无法找出一个可以返回所有问题结果的查询,即使对于没有回答新问题的老用户也是如此。

问题是旧用户在用户问题表中没有条目,因此如何才能获得默认的'不回答'对于未在用户问题表中输入值的旧用户?

见下面的表结构

用户表

id | username
0  | louis

用户问题表

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

问题表

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

答案表

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

2 个答案:

答案 0 :(得分:1)

您希望使用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

答案 1 :(得分:1)

我会得到所有问题,请加入答案和用户问题,并与用户进行交叉加入:

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