34,590
社区成员
发帖
与我相关
我的任务
分享
---测试数据---
if object_id('[t_A]') is not null drop table [t_A]
go
create table [t_A]([color] varchar(3),[size] varchar(2),[itemno] varchar(7))
insert [t_A]
select 'aaa','34','xU79910' union all
select 'bbb','U','LCas910' union all
select 'ccc','54','bb9910' union all
select 'ddd','23','er79910'
if object_id('[t_B]') is not null drop table [t_B]
go
create table [t_B]([color] varchar(3),[size] varchar(2),[itemno] varchar(7),[barcode] varchar(12))
insert [t_B]
select 'aaa','34','xU79910','123456789012' union all
select 'aaa','34','xU79910','1234567' union all
select 'bbb','U','LCas910','34567890' union all
select 'ccc','54','bb9910','098765432123' union all
select 'ddd','23','er79910','012345678901' union all
select 'ddd','23','er79910','0123456'
---查询---
select a.color,a.size,a.itemno,isnull(b.barcode,a.itemno) as barcode
from t_A a
left join
(select color,size,itemno,barcode
from t_B where len(barcode)=12) b
on a.color=b.color and a.size=b.size and a.itemno=b.itemno
---结果---
color size itemno barcode
----- ---- ------- ------------
aaa 34 xU79910 123456789012
bbb U LCas910 LCas910
ccc 54 bb9910 098765432123
ddd 23 er79910 012345678901
(所影响的行数为 4 行)
select b.color,b.size,b.itemno,isnull(a.barcode,b.itemno)
from t_B b
left join t_A a on a.color=b.color and a.size=b.size and a.itemno=b.itemno
select *
from t_B
where len(barcode)=12