如何选择存在交集的两个表,请高手指教!!!!!!!!!!
如下两个表:
table1:
c1 c2
1 a,b,c,d
2 r,e,g,j,d
3 a,b
4 a
5 a,y
table2:
c3 c4
1 b,y
选出所有上面两个表存在交集的数据的SQL要如何写
得到的结果应该是
从table1.c1中选取记录为
1
3
5
由于1,3,5中不是包含b就是包含y
请高手指教!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
问题点数:80、回复次数:3Top
1 楼didoleo(冷月无声)回复于 2005-02-04 19:00:59 得分 40
create table tb1
(c1 int,c2 varchar(1000))
insert into tb1
select 1 , 'a,b,c,d' union all
select 2 , 'r,e,g,j,d' union all
select 3 , 'a,b' union all
select 4 , 'a' union all
select 5 , 'a,y'
create table tb2
(c3 int,c4 varchar(1000))
insert into tb2
select 1 , 'b,y'
--插分处理
--处理临时表
drop table #t2
declare @i int
declare @j int
select @i=max(len(c2)) from tb1
select @j=max(len(c4)) from tb2
set rowcount @i
select id=identity(int) into #t1 from syscolumns a,syscolumns b
set rowcount @j
select id=identity(int) into #t2 from syscolumns a,syscolumns b
set rowcount 0
select * from (
select a.c1,
c2=substring(a.c2,b.id,charindex(',',a.c2+',',b.id)-b.id)
from tb1 a,#t1 b
where substring(','+a.c2,b.id,1)=','
) a where
exists (
--order by a.c1,b.id
select 1 from (
select
c4=substring(a.c4,b.id,charindex(',',a.c4+',',b.id)-b.id)
from tb2 a,#t2 b
where substring(','+a.c4,b.id,1)=','
) b where a.c2=b.c4
)
--------------------------------
1 b
3 b
5 y
(所影响的行数为 3 行)Top
2 楼didoleo(冷月无声)回复于 2005-02-04 19:04:32 得分 40
--改一点,当中的drop table #t2不要
create table tb1
(c1 int,c2 varchar(1000))
insert into tb1
select 1 , 'a,b,c,d' union all
select 2 , 'r,e,g,j,d' union all
select 3 , 'a,b' union all
select 4 , 'a' union all
select 5 , 'a,y'
create table tb2
(c3 int,c4 varchar(1000))
insert into tb2
select 1 , 'b,y'
declare @i int
declare @j int
select @i=max(len(c2)) from tb1
select @j=max(len(c4)) from tb2
set rowcount @i
select id=identity(int) into #t1 from syscolumns a,syscolumns b
set rowcount @j
select id=identity(int) into #t2 from syscolumns a,syscolumns b
set rowcount 0
select * from tb1 where c1 in (
select a.c1 from (
select a.c1,
c2=substring(a.c2,b.id,charindex(',',a.c2+',',b.id)-b.id)
from tb1 a,#t1 b
where substring(','+a.c2,b.id,1)=','
) a where
exists (
select 1 from (
select
c4=substring(a.c4,b.id,charindex(',',a.c4+',',b.id)-b.id)
from tb2 a,#t2 b
where substring(','+a.c4,b.id,1)=','
) b where a.c2=b.c4
)
)
--------------------------------
c1 c2
1 a,b,c,d
3 a,b
5 a,y
(所影响的行数为 3 行)Top
3 楼yuekai(BTS)回复于 2005-02-04 19:38:33 得分 0
感谢,先看看,马上结贴Top




