右连接不赋值null

时间:2014-04-07 15:05:26

标签: sql database sql-server-2008

我有两张桌子:

select * from CallTypeDescription
select * from CallTypeDetails 

enter image description here

我想在idjob上显示idcalltype的所有记录。

例如

如果CallTypeDescription中的idJob为96且idCallType为4,则应显示记录:

enter image description here

如果idJob为94(即callType描述中不存在)且idCallType为4,则结果应为:

Title        Value   idJob

test qu1      Null    Null

test qu2      Null    Null 

为此我试过:

select a.Title,b.Value,b.idJob from  CallTypeDescription b
right join CallTypeDetails a
on a.idCallType=b.idCallType
and a.idDetails=b.idCallTypeDetail
where a.idCallType=4 and b.idJob=96 

但是给了我结果:

enter image description here

它还应该添加另一行test qu2 null null。

请帮助我。

修改

select a.Title,b.Value,b.idJob from  CallTypeDescription b
    right join CallTypeDetails a
    on a.idCallType=b.idCallType
    and a.idDetails=b.idCallTypeDetail
    and a.idCallType=4 
    where  b.idJob=96 

2 个答案:

答案 0 :(得分:2)

看起来你是在追求这种效果(SQL小提琴:http://sqlfiddle.com/#!3/8f98e/10):

select
  a.Title,b.Value,b.idJob
from
  (
    select
      IdDesc, 
      IdCallType,
      IdJob,
      IdCallTypeDetail,
      Value
    from
      CallTypeDescription
    where
      IdJob = 96 --or 94
  ) b
right outer join
  CallTypeDetails a
on
  a.idCallType=b.idCallType
and
  a.idDetails=b.idCallTypeDetail
where
  a.idCallType=4

您是否有理由选择使用右连接而不是左连接?

答案 1 :(得分:1)

删除约束查询的行只返回idDetails和isCallTypeDetail相等的行:

select a.Title,b.Value,b.idJob from CallTypeDescription b inner join CallTypeDetails a on a.idCallType=b.idCallType where a.idCallType=4 and b.idJob=96