日期:2014-05-18  浏览次数:20479 次

这种多条件都满足时的查询怎么写?

有表tab

id,f1,f2
1,a,a
1,b,b
1,c,c
2,d,d

查出满足条件
(f1=a and f2=a) 且 (f1=b and f2=b) 

的所有结果
id,f1,f2
1,a,a
1,b,b
1,c,c

------解决方案--------------------
SQL code

--> 测试数据:[tb]
if object_id('[tb]') is not null 
drop table [tb]
create table [tb](
[id] int,
[f1] varchar(1),
[f2] varchar(1)
)
insert [tb]
select 1,'a','a' union all
select 1,'b','b' union all
select 1,'c','c' union all
select 2,'d','d'

select * from tb
where f1=f2 and f1 in('a','b','c')
/*
id    f1    f2
---------------------
1    a    a
1    b    b
1    c    c
*/

------解决方案--------------------
SQL code
if object_id('[tab]') is not null drop table [tab]
go
create table [tab]([id] int,[f1] varchar(1),[f2] varchar(1))
insert [tab]
select 1,'a','a' union all
select 1,'b','b' union all
select 1,'c','c' union all
select 2,'d','d'

select * from tab
where id in(
  select id 
  from tab 
  where (f1='a' and f2='a' or f1='b' and f2='b') 
  group by id 
  having count(distinct f1)=2
)

/**
id          f1   f2
----------- ---- ----
1           a    a
1           b    b
1           c    c

(3 行受影响)
**/