日期:2014-05-19  浏览次数:20424 次

(100分求解)两张表某字段的匹配问题
表A(海量数据库)结构如下:
field1       field2     ....
a1                   1
a2                   2
a3                   3
....
an                   n

表B结构如下:
field1     field2       ....
a1,a2           b1
a4,a5,a8     b2
....
am                 bm

请问高手,如何根据表B中字段field1中的值(以逗号分隔)找出海量表A中匹配的记录?如表B中a1,a2匹配表A中的两条记录。


------解决方案--------------------
where charindex( ', '+a.field1+ ', ' , ', '+b.field1+ ', ') > 1
------解决方案--------------------
一楼的方法简单:

select a.*,b.* from a,b where charindex( ', '+a.field1+ ', ', ', '+b.field1+ ', ')> 1

------解决方案--------------------
declare @t1 table(field1 varchar(10),field2 varchar(10))
insert @t1 select 'a1 ', '1 '
union all select 'a2 ', '2 '
union all select 'a3 ', '3 '

declare @t2 table(field1 varchar(10),field2 varchar(10))
insert @t2 select 'a1,a2 ', 'b1 '
union all select 'a4,a5,a8 ', 'b2 '

if object_id( 'tempdb..#t1 ')> 0
drop table #t1

select top 50 id=identity(int,1,1) into #t1 from syscolumns

if object_id( 'tempdb..#t2 ')> 0
drop table #t2
select field1=substring(a.field1,b.id,charindex( ', ',a.field1+ ', ',b.id)-b.id)
into #t2
from @t2 a,#t1 b
where b.id <len(a.field1+ 'a ')
and charindex( ', ', ', '+a.field1,b.id)=b.id

select a.field1,b.field2
from #t2 a,@t1 b
where a.field1=b.field1
------解决方案--------------------
select a.* from A a cross join B b where charindex(a.field1,b.field1)> 0