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

SQl语句 两表两字段包含集合



表A中a字段在表B中b字段包含的集合如图:B中包含456的查出来,就是证明两个有关联,两表的集合
SQL

------解决方案--------------------
declare @n int
select @n=count(*)
from a
where exists(select 1 from b where charindex(a.a,b.b)>0)

if isnull(@n,0)>0
print '有关联'
else
print '无关联'

------解决方案--------------------
create table a (a varchar(20))
insert into a values('123')
insert into a values('245')
insert into a values('445')
insert into a values('4542')
insert into a values('456')
create table b (b varchar(20))
insert into b values('123456')
insert into b values('55456')
insert into b values('45896')
go


select a.a , b.b from a , b where charindex(a.a , b.b) > 0

/*
a                    b                    
-------------------- -------------------- 
123                  123456
456                  123456
456                  55456

(所影响的行数为 3 行)
*/

select a.a , b.b from a , b where b.b like '%' + a.a + '%'

/*
a                    b                    
-------------------- -------------------- 
123                  123456