簡體   English   中英

在where條件中具有所有必需值的Oracle SQL查詢

[英]Oracle sql query with all mandatory values in where condition

我想在ORACLE中編寫一個選擇查詢,該查詢僅在條件存在的情況下給出的所有值都將返回記錄。 例如

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

現在,我想編寫此查詢,以便僅在所有3個empid存在時才返回值。 它將類似於AND條件,即empid = 7521和empid = 7566以及empid =7698。如果不存在任何一個值,則此查詢不應獲取任何行。

再次運行相同的查詢,作為嵌套選擇,並計算其記錄

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

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。 ..

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM