筛选查询
/*建立test1,test2*/
create table test1
(test1id int ,col1 char(1),col2 char(1),col3 char(1))
insert into test1 (test1id,col1,col2,col3)
select 1,'a','x' ,'l'
union all
select 2,'b','x' ,'l'
union all
select 3,'c','x' ,'m'
union all
select 4,'d','x' ,'m'
union all
select 5,'a','y' ,'n'
--drop table test1
--drop table test2
create table test2
(test2id int ,col1 char(1),col2 char(1),col4 char(2))
insert into test2 (test2id,col1,col2,col4)
SELECT 11,'a','x' ,'ee'
UNION ALL SELECT 12,'c','x','ee'
UNION ALL select 1,'b','x' ,'ee'
union all
select 2,'b','x' ,'ff'
union all
select 3,'a','x' ,'ff'
union all
select 4,'a','y' ,'gg'
union all
select 5,'b','y' ,'gg'
union all
select 6,'c','y' ,'hh'
union all
select 7,'a','z','hh'
--select * from test1
----select * from test2
--查询一 test2中a.col2=b.col2 ,并且筛选包含test1 a.col3='l'所对应的col1中的两条记录'a','b'
select * from test2 b
where exists(select 0 from test1 a where a.col2=b.col2 and a.col3='l' and a.col1='a')
and exists(select 0 from test1 a where a.col2=b.col2 and a.col3='l' and a.col1='b')
--查询二 test2中a.col2=b.col2 ,并且筛选包含test1 a.col3='m'所对应的col1中的两条记录'c','d'
select * from test2 b
where exists(select 0 from test1 a where a.col2=b.col2 and a.col3='m' and a.col1='d')
and exists(select 0 from test1 a where a.col2=b.col2 and a.col3='m' and a.col1='d')
--查询三 test2中a.col2=b.col2 ,并且筛选包含test1 a.col3='n'所对应的col1中的记录'a'
select * from test2 b
where exists(select 0 from test1 a where a.col2=b.col2 and a.col3='n' and a.col1='a')
--有没有办法一次查询出这些记录,并且不直接引用'l','a','m'.等记录