表Aid uid title
1 1 aa
2 1 bb
3 cc
4 2 dd
5 ee
6 2 ff
7 3 gg表Bid name
1 张三
2 李四
3 黄五用一句SQL语句取出表A 的数据
根据uid 的值去表B 取name如果uid 值 存在就去表B 取name
如果不存在 就不去表B取name 但仍然取表A 的其他值
1 1 aa
2 1 bb
3 cc
4 2 dd
5 ee
6 2 ff
7 3 gg表Bid name
1 张三
2 李四
3 黄五用一句SQL语句取出表A 的数据
根据uid 的值去表B 取name如果uid 值 存在就去表B 取name
如果不存在 就不去表B取name 但仍然取表A 的其他值
if not object_id('Tempdb..#T') is null
drop table #T
Go
Create table #T([id] int,[uid] nvarchar(2),[title] nvarchar(2))
Insert #T
select 1,'1','aa' union all
select 2,'1','bb' union all
select 3,'cc',null union all
select 4,'2','dd' union all
select 5,'ee',null union all
select 6,'2','ff' union all
select 7,'3','gg'
Go--> --> (Ben)生成測試數據
if not object_id('Tempdb..#T2') is null
drop table #T2
Go
Create table #T2([id] int,[name] nvarchar(2))
Insert #T2
select 1,'张三' union all
select 2,'李四' union all
select 3,'黄五'
Go
select a.id,isnull(name,convert(char(3),a.uid )),title from #T a
left join #T2 b on a.uid=convert(char(3),b.id )
if object_id('tempdb.dbo.#a') is not null drop table #a
create table #a (id int,uid int,title varchar(11))
insert into #a
select 1,1,'aa' union all
select 2,1,'bb' union all
select 3,null,'cc' union all
select 4,2,'dd' union all
select 5,null,'ee' union all
select 6,2,'ff' union all
select 7,3,'gg'
--> 测试数据: #b
if object_id('tempdb.dbo.#b') is not null drop table #b
create table #b (id int,name varchar(11))
insert into #b
select 1,'张三' union all
select 2,'李四' union all
select 3,'黄五'select a.id,name=isnull(b.name,ltrim(a.uid)),a.title from #a a left join #b b on a.uid=b.id
/*
id name title
----------- ----------- -----------
1 张三 aa
2 张三 bb
3 NULL cc
4 李四 dd
5 NULL ee
6 李四 ff
7 黄五 gg
*/