Oracle sql查询,其中包含where条件中的所有必需值

时间:2011-10-28 07:51:23

标签: sql oracle

我想在ORACLE中编写一个select查询,只有在where条件中给出的所有值都存在时才会返回记录。 E.g。

select * from emp where empid in (7521,7566,7698)

现在我想编写这个查询,以便只有当所有3个empid都存在时它才会返回值。这将是AND条件,即empid = 7521和empid = 7566和empid = 7698.如果任何一个值不存在,那么此查询不应该获取任何行。

2 个答案:

答案 0 :(得分:4)

再次运行相同的查询,作为嵌套选择,并计算其记录

select * from emp 
where empid in (7521, 7566, 7698)
and 3 = (select count(*) from emp where empid in (7521, 7566, 7698))

或者,对原始结果使用分析函数并检查:

select * from (
  select emp.*, count(*) over() as cnt
  from emp where empid in (7521, 7566, 7698)
)
where cnt = 3

答案 1 :(得分:3)

Lukas版本的扩展,您只需要编写一次ID:

with emp_ids as (
   select 7521 as eid from dual
   union all 
   select 7566 from dual
   union all
   select 7698 from dual
)
select * 
from (
  select emp.*, 
         count(*) over() as cnt
  from emp_new emp
  where empid in (select eid from emp_ids)
)
where cnt = (select count(*) from emp_ids);

在这些情况下,我总是错过其他DBMS中可用的标准行构造函数,我只需编写VALUES (7521), (7566), (7698)即可生成具有所需值的虚拟表,而无需使用DUAL ...