求一 sql语句 多表查询关联问题

bxbacn 2009-05-04 02:51:40
tableA

id sid title
1 1 在在
2 0 在有枯
3 2 在时有
4 1 jkf

tableB
sid sname
1 分类1
2 分类2

常规语句
select tableA.id,tableA.sid,tableA.title,tableB.sname from tableA,tableB where tableA.sid=tableB.sid


现在要求当tableA表中sid为0时,默认sname="默认",而不是id为2那条记录不显示

希望结果如下

查询结果:
id sid title sname
1 1 在在 分类1
2 0 在有枯 默认
........
...全文
127 15 打赏 收藏 转发到动态 举报
写回复
用AI写文章
15 条回复
切换为时间正序
请发表友善的回复…
发表回复
bxbacn 2009-05-05
  • 打赏
  • 举报
回复
试试结贴后还能不能回复
zzxap 2009-05-04
  • 打赏
  • 举报
回复
select a.id,a.sid,a.title,case when a.sid='0' or a.sid is null or a.sid="" then '默认' else b.sname end as sname from tableA a,tableB b where a.sid=b.sid

ljhcy99 2009-05-04
  • 打赏
  • 举报
回复
select TableA.id,tableA.sid, tableA.title,
(case when tableA.sid=0 and tableB.sname=null then '默认' else tableB.sname end) sname
from tableA left outer join tableB
on(tableA.sid=tableB.sid)
bxbacn 2009-05-04
  • 打赏
  • 举报
回复
是我的错,1楼正解 试验通过
bxbacn 2009-05-04
  • 打赏
  • 举报
回复
请求 cpp2017 zzxap等高手们

给我写个完整版,当tableA表中sid=0时,而 tableB表中没有sid=0的记录时,如何显示出tableA表中所有记录,并将无关联记录的sname显示为 默认
bxbacn 2009-05-04
  • 打赏
  • 举报
回复
都有问题,当我tableA 表中的 sid 为 0时,因为 tableB表没有为0 的sid,所以那条sid=0的记录就将不会显示
reoaiq 2009-05-04
  • 打赏
  • 举报
回复
二楼的回复正确
cyz9977 2009-05-04
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 cpp2017 的回复:]
select tableA.id,tableA.sid,tableA.title,ISNULL(tableB.sname ,'默认')


from tableA left outer join tableB on
tableA.sid=tableB.sid
[/Quote]

左外連接~~

ISNULL是sqlserver的函數~~
ljhcy99 2009-05-04
  • 打赏
  • 举报
回复

select TableA.id,tableA.sid, tableA.title,(case when tableB.sname = 0 then '默认' else tableB.sname end) sname
from tableA left outer join tableB
on(tableA.sid=tableB.sid)
zy_1985 2009-05-04
  • 打赏
  • 举报
回复
学习.
llsen 2009-05-04
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 zzxap 的回复:]
select a.id,a.sid,a.title,case when a.sid='0' then '默认' else b.sname end as sname from tableA a,tableB b where tableA.sid=tableB.sid
[/Quote]

select a.id,a.sid,a.title,case when a.sid='0' then '默认' else b.sname  end as sname from tableA a,tableB b where tableA.sid=tableB.sid


用case when
bxbacn 2009-05-04
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 cpp2017 的回复:]
select tableA.id,tableA.sid,tableA.title,ISNULL(tableB.sname ,'默认')

from tableA left outer join tableB on
tableA.sid=tableB.sid
[/Quote]

isnull 不行,我不是null值,而是0值,楼下的可行,但不知道有没有像isnull这样的系统自带函数
sayluyun 2009-05-04
  • 打赏
  • 举报
回复
楼上的很精辟··
zzxap 2009-05-04
  • 打赏
  • 举报
回复
select a.id,a.sid,a.title,case when a.sid='0' then '默认' else b.sname end as sname from tableA a,tableB b where tableA.sid=tableB.sid
cpp2017 2009-05-04
  • 打赏
  • 举报
回复
select tableA.id,tableA.sid,tableA.title,ISNULL(tableB.sname ,'默认')


from tableA left outer join tableB on
tableA.sid=tableB.sid

62,041

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术交流专区
javascript云原生 企业社区
社区管理员
  • ASP.NET
  • .Net开发者社区
  • R小R
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

.NET 社区是一个围绕开源 .NET 的开放、热情、创新、包容的技术社区。社区致力于为广大 .NET 爱好者提供一个良好的知识共享、协同互助的 .NET 技术交流环境。我们尊重不同意见,支持健康理性的辩论和互动,反对歧视和攻击。

希望和大家一起共同营造一个活跃、友好的社区氛围。

试试用AI创作助手写篇文章吧