我想请教一条SQL语句。
是这样的,有一个数据库,如图:里面有两张表,Stu和Info,其中Stu的ID和Info的UID是主外键关系,然后Info表的Re可以为空。
我现在想得到这样的查询结果:
  通过主外键关系,如果Stu表中对应ID在Info表中的Re为空的话,得到的是Stu表中的ID,Name,Age
如果Info表中的Re不为空的话,得到的是Stu表中的ID,Age,和Info表中的Re。
现有数据如下,请教SQL语句一条;
Stu表:  Info表:我通过ID = 2来查询到这样的字段,Stu表中的ID,Age,和Info表中的'张三',也就是Re。
如果ID = 1,也就是Info表中对应的Re为空,则得到Stu表中的所有字段(ID,Name,Age)。请教了!!

解决方案 »

  1.   

    select id,name ,case when re is null then cast(age as varchar(3)) else re end 
    from  stu left join info on stu.id = info.uid
      

  2.   

    select stu.id,isnull(info.re,stu.name) as name,age
    from  stu left join info on stu.id = info.uid
      

  3.   

    select a.id,(case when b.Re is null then a.Name else b.Re end) as Name ,a.age from Stu a,Info b where a.id = b.uid应该是这样没建表没测试
      

  4.   

    select id,name,age case when re is null then null else re end 
    from  stu inner join info on stu.id = info.uid
      

  5.   

    select id,name,age case when re is null then null else re end 
    from  stu inner join info on stu.id = info.uid
      

  6.   


    select a.ID,(case when b.Re is null then a.Name else b.Re end) as Name,
    a.Age from Stu as a left join Info as b on a.ID=b.Uid
      

  7.   

    这样也行select a.ID,isnull(b.Re,a.Name) as Name,a.Age from stu as a left join Info as b on a.ID=b.Uid
      

  8.   

    select a.id,a.name ,(case when b.re is null then cast(age as varchar) else re end) as re
    from  stu a left join info b on a.id = b.uid