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

sql server 查询
表test
ID,A,B
50,hello,world
51,hell,word
表out
ID,C
50,hello
50,world hello
51,hell
51,world
51,lleh

查询表test中某个ID对应的A、B均在表out中具有相同ID的C中模糊出现的记录
比如test中,ID=50,A=hello,B=world
out中,ID=50的C有hello和world hello
test的A=hello与C的hello匹配
test的B=world与C的world hello模糊匹配(若C="abc world hello"也是与B=world匹配的)
所以test中第一条记录符合条件,输出
test的ID=51的记录显然不符合条件
求sql语句

------解决方案--------------------

create table #ta(ID int,A varchar(10),B varchar(10))
insert into #ta
select 50,'hello','world'
union all select 51,'hell','word'

create table #tb(ID int,C varchar(100))
insert into #tb
select 50,'hello'
union all select 50,'world hello'
union all select 51,'hell'
union all select 51,'world'
union all select 51,'lleh'

select a.*
from #ta a
inner join #tb b on a.A=b.C
inner join #tb c on a.B=c.C
drop table #ta,#tb


/*
ID   A     B
------------------------
50 hello world
*/