日期:2014-05-19  浏览次数:20481 次

再问:SQL查询问题:如何让不存在的记录也显示?
我昨天提问,表达不清楚(http://community.csdn.net/Expert/topic/5442/5442197.xml?temp=.6215479),现在重新开帖


表a:
id             cname
1                 张
2                 林
3                 王
4                 刘

表b:
id             charge     note
1                 30             晚班
3                 80             加班

如何实现如下结果(按条件加班查询):
id                 cname             charge
1                     张                       0或null或干脆显示空白
2                     林                       0或null或干脆显示空白
3                     王                     80
4                     刘                       0或null或干脆显示空白


我的sql:
Select   A.id,A.cname,IsNull(B.charge,   0)   As   charge  
From   A  
Left   Outer     Join   B  
On   A.id   =   B.id
where   b.note= '加班 '

查询结果:

3                     王                     80       加班

其他没有了



------解决方案--------------------
Select A.id,A.cname,IsNull(B.charge, 0) As charge
From A , B where b.note= '加班 ' and A.id *= B.id

------解决方案--------------------
這麼修改即可

Select A.id,A.cname,IsNull(B.charge, 0) As charge
From A
Left Outer Join B
On A.id = B.id
And b.note= '加班 ' -- Where 修改為And即可

------解决方案--------------------
Select A.id,A.cname,IsNull(B.charge, 0) As charge
From A , B
where b.note= '加班 ' and
A.id *= B.id --- 这句的*号在那边就是显示那边的记录,也就是一那边的记录为主
------解决方案--------------------
drop table a,b
go
create table a(id int,cname varchar(20))
insert into a
select 1, '张 '
union select 2, '林 '
union select 3, '王 '
union select 4, '刘 '

create table b(id int,charge int,note varchar(20))
insert into b
select 1,30, '晚班 '
union all select 3,80, '加班 '


select a.id,a.cname,(select charge from b where a.id=b.id and note= '加班 ') as charge
from a

/*
id cname charge
----------- -------------------- -----------
1 张 NULL
2 林 NULL
3 王 80
4 刘 NULL

(所影响的行数为 4 行)