个人认为是个难题!

ilovewebtime 2010-08-15 12:05:10
表A:
id uid
1 1000
2 1001
3 1001
4 1002

表B:
id uid img
1 1000 img1
1 0 img2
1 1005 img3
2 1003 img4
2 0 img5

如何得到以下这样的查询结果

id uid img
1 1000 img1
2 1001 img5
3 1001 null
4 1002 null

目的说明:以A表的id为主查B表中相应的img,关键问题是如何能让uid按以下优先顺序获取,并只取其1(1:A.uid=B.uid 2:B.uid=0)
...全文
60 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
昵称被占用了 2010-08-15
  • 打赏
  • 举报
回复
补完整点

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
昵称被占用了 2010-08-15
  • 打赏
  • 举报
回复
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
xman_78tom 2010-08-15
  • 打赏
  • 举报
回复

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;
duanzhi1984 2010-08-15
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 ilovewebtime 的回复:]
感觉效率都不高呀,还有其它办法吗?
[/Quote]

哥们以上的效率都不错了。。。

ilovewebtime 2010-08-15
  • 打赏
  • 举报
回复
感觉效率都不高呀,还有其它办法吗?
SQLCenter 2010-08-15
  • 打赏
  • 举报
回复
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

34,590

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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