情况是这样的.
原来有二个表如 a 和 b .
假设A表有字段
id,name,mid,cid,fid
表B有字段
id,time,fid,aid
二表之间的关系是: A 表有的记录,在B表不一定有也可能有很多条(这里可能是cid,mid,fid的值不同),B表中的 fid 是对应(mid,cid,fid)中不确定哪个(哪个不为空就是哪个),aid是表A的ID.
表A中,mid或cid或 fid 其中必然有一个不为空,同时也不确定其它二个字段值是为null还是0,
现在有什么好办法能够用A表与B表关联,返回一个结果包括id(A表),name,time(B表)字段的记录集吗?
谢谢!

解决方案 »

  1.   

    declare @t table([id] int,[name] varchar(10),mid int,cid int,fid int)
    declare @a table([id] int,[time] varchar(10),fid int,aid int)insert into @t select 1,'aa',13,12,6
    insert into @t select 2,'bb',12,1,5
    insert into @t select 3,'cc',11,3,1
    insert into @t select 5,'ee',5,13,10insert into @a select 12,'2004-01-12',4,1
    insert into @a select 15,'2003-11-12',6,2
    insert into @a select 20,'2006-01-12',8,10select a.[id],a.[name],b.[time] from @t a,@a b where a.id=b.aid
      

  2.   

    这样不对啦,需求时有说明 A 表和B表是 1 对多关系!
    并且,那个 mid,cid,fid 都没有确认哪个不为空(null)或0.
    不过谢谢您的回复.
      

  3.   

    我自已写,但出错,原SQL如下:
    select 
     case not mid is null and mid<>0 then mid
     case not cid is null and cid<>0 then cid
     case not fid is null and fid<>0 then fid
     else mid
    end as a.ffid,a.id,b.time
    from a 
    left join b 
    on a.id=b.aid and a.ffid=b.fid
    可是,运行不了,提示第一行 . 附近有语法错误,我搞了半天.晕菜
      

  4.   

    select 
     case when (mid is not null and mid<>0) then mid
          when (cid is not null and cid<>0) then cid
          when (fid is not null and fid<>0) then fid
     else mid
    end as ffid,a.id,b.time
    from a left join b 
    on 
    a.id=b.aid and a.ffid=b.fid
      

  5.   

    其实这个句子中的 a.ffid 是 case 出来的.
    好像不能用,在SQL企业管理器里执行都通不过.