请教一条SQL语句

whowhen21 2009-04-02 03:50:42
我想请教一条SQL语句。
是这样的,有一个数据库,如图:

里面有两张表,Stu和Info,其中Stu的ID和Info的UID是主外键关系,然后Info表的Remark可以为空。
我现在想得到这样的查询结果:
通过主外键关系,如果Stu表中对应ID在Info表中的Remark为空的话,得到的是Stu表中的ID,Name,Age
如果Info表中的Remark不为空的话,得到的是Stu表中的ID,Age,和Info表中的Remark。
现有数据如下,请教SQL语句一条;
Stu表: Info表:

我通过ID = 2来查询到这样的字段,Stu表中的ID,Age,和Info表中的'张三',也就是Remark。
如果ID = 1,也就是Info表中对应的Remark为空,则得到Stu表中的所有字段(ID,Name,Age)。

请教了!!
...全文
115 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
lybelmont 2009-04-02
  • 打赏
  • 举报
回复
不错 大家的方法都能实现
wuyq11 2009-04-02
  • 打赏
  • 举报
回复
select a.id,a.name ,(case when b.remark is null then cast(age as varchar) else remark end) as remark
from stu a left join info b on a.id = b.uid
wangping_li 2009-04-02
  • 打赏
  • 举报
回复
这样也行

select a.ID,isnull(b.Remark,a.Name) as Name,a.Age from stu as a left join Info as b on a.ID=b.Uid

wangping_li 2009-04-02
  • 打赏
  • 举报
回复

select a.ID,(case when b.Remark is null then a.Name else b.Remark end) as Name,
a.Age from Stu as a left join Info as b on a.ID=b.Uid
zhongti 2009-04-02
  • 打赏
  • 举报
回复
select id,name,age case when remark is null then null else remark end
from stu inner join info on stu.id = info.uid
zhongti 2009-04-02
  • 打赏
  • 举报
回复
select id,name,age case when remark is null then null else remark end
from stu inner join info on stu.id = info.uid
kenesyu 2009-04-02
  • 打赏
  • 举报
回复
select a.id,(case when b.Remark is null then a.Name else b.Remark end) as Name ,a.age from Stu a,Info b where a.id = b.uid


应该是这样没建表没测试
fiveandfive 2009-04-02
  • 打赏
  • 举报
回复
不看错,只冲你认真地贴图,顶.
jiyan1221 2009-04-02
  • 打赏
  • 举报
回复
select stu.id,isnull(info.remark,stu.name) as name,age
from stu left join info on stu.id = info.uid
moonshineidolon 2009-04-02
  • 打赏
  • 举报
回复
select id,name ,case when remark is null then cast(age as varchar(3)) else remark end
from stu left join info on stu.id = info.uid

110,534

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

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