日期:2014-05-17  浏览次数:20477 次

两张表合成的问题

A表

   名称
   安徽江淮汽车集团有限公司
   广东健力宝集团有限公司
   海尔集团公司
   国家电网

B表
  名称 
  海尔集团
  健力宝
  加多宝
  哈药集团有限公司
  北京同仁堂
  国家电网公司

需合成C表
   安徽江淮汽车集团有限公司
   广东健力宝集团有限公司
   海尔集团公司
   加多宝
  哈药集团有限公司
  北京同仁堂
  国家电网公司

就是A表根据关键字去除B表里面的
B表根据关键字去除A表里面的 得到了C表。 用like好像不行



------最佳解决方案--------------------
select * into #tb from A
union all
select * from B

delete a from #tb a 
  where exists(select 1 from #tb where 名称 like '%'+a.名称+'%' and len(名称)>len(a.名称)) 

select * from #tb
------其他解决方案--------------------
select * 
from 
a inner join b on a.主键=b.主键
inner join c on b.主键=c.主键

------其他解决方案--------------------
select 名称 
from TBA a 
where not exists(select 1 from TBB where 名称 like '%'+a.名称+'%')
union all
select 名称 
from TBB b 
where not exists(select 1 from TBA where 名称 like '%'+b.名称+'%')

------其他解决方案--------------------
引用:
SQL code?



1234567

select 名称  from TBA a  where not exists(select 1 from TBB where 名称 like '%'+a.名称+'%') union allselect 名称  from TBB b  where not exists(select 1 from TBA where 名称 like '%'+b……

+1
------其他解决方案--------------------

if OBJECT_ID('tb1') is not null
drop table tb1
if OBJECT_ID('tb2') is not null
drop table tb2
go
create table tb1(name varchar(40))
create table tb2(name varchar(40))
insert into tb1
values( '安徽江淮汽车集团有限公司'),
('广东健力宝集团有限公司'),
  ('海尔集团公司'),
   ('国家电网')
insert into tb2
select  '海尔集团'  union all 
select  '健力宝' union all
select  '加多宝' union all
select  '哈药集团有限公司' union all
select    '北京同仁堂' union all
select  '国家电网公司'

;with sel as
(select name from tb1 union  all 
select name from tb2)
select distinct name from sel except(select a.name from tb1 a,tb2 b
where CHARINDEX(a.name,b.name)>0 union all
select b.name from tb1 a,tb2 b
where CHARINDEX(b.name,a.name)>0 )

/*
name
----------------------------------------
安徽江淮汽车集团有限公司
北京同仁堂
广东健力宝集团有限公司
国家电网公司
哈药集团有限公司