34,590
社区成员
发帖
与我相关
我的任务
分享
select id,uid
,(select top 1 img from b where b.id = a.id order by case when b.uid = a.uid then 0 else 1 end,case when b.uid = 0 then 0 else 1 end,b.uid) as img
from a
order by id
select id,uid
,(select top 1 img from b where b.id = a.id order by case when b.uid = a.uid then 0 else 1 end,case when b.uid = 0 then 0 else 1 end,b.uid)
from a
declare @a table(id int, uid int);
insert into @a
select 1,1000 union all select 2,1001 union all
select 3,1001 union all select 4,1002;
declare @b table(id int,uid int,img varchar(10));
insert into @b
select 1,1000,'img1' union all select 1,0,'img2' union all
select 1,1005,'img3' union all select 2,1003,'img4' union all
select 2,0,'img5';
select id,uid,
(select top 1 img from @b where id=a.id and (uid=a.uid or uid=0) order by uid desc)
from @a a;
select a.id,a.uid,isnull(b1.img,b2.img)
from @a a left join @b b1
on a.id=b1.id and a.uid=b1.uid
left join @b b2
on a.id=b2.id and b2.uid=0;
select a.*, b.img from tbA a left join tbB b on a.id = b.id
and b.uid = case when exists (select 1 from tbB where id=a.id and uid=a.uid) then a.uid else 0 end