【问题标题】:Joining Table that has no value连接没有价值的表
【发布时间】:2015-03-16 01:10:59
【问题描述】:

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

问题是老用户在 用户问题表 中没有条目,所以我怎样才能为没有在 中输入值的老用户获得默认的“不回答” >用户问题表

见下表结构

用户表

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

【问题讨论】:

    标签: sql database join unique


    【解决方案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

    【讨论】:

      【解决方案2】:

      您想使用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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-04-09
        • 1970-01-01
        • 2016-08-29
        • 1970-01-01
        • 1970-01-01
        • 2011-09-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多