[英]Oracle PL/SQL: Create a short circuit query
我有點老派,所以我稱之為短路。
但我在 Oracle 中有 3 個表。 我還有一個“ProcessFlag”。 如果表中的任何數據符合我的條件,我想設置 procesdFlag = 1。
我顯然可以用 if 和 else 語句來做到這一點。
select count(*) into myCounter from from Table1 where processflag = 1;
if myCounter = 0 then
select count(*) into myCounter from Table2 where processflag = 1;
if myCounter = 0 then
select count(*) into myCounter from Table3 where processflag = 1;
if myCounter = 0 then
processFlag = 0;
else
processFlag = 1;
end if
else
processFlag = 1;
end if
else
processFlag = 1;
end if
所以,假設我所有的 if/eles 都是正確的,我想你明白我在做什么。 如果在任何表中有任何行具有 processFlag = 1,那么我要處理。
這只是一個演示的小例子,但我的現實世界有大約 10 個表,如果我不需要的話,我真的不想嵌套那么深的 if/else 語句。 而且這些表有的數據很多,所以如果第1個表查到東西,就不用再去查后續表了(這就是為什么我叫它短路,因為一查到東西,就沒有需要處理剩余的代碼)。
如果在 Oracle 中有更清潔/有效的方法來做到這一點?
短路查詢的用case when
下:
Select case
when (select 1 from table1 where processflag = 1 and rownum =1) = 1 -- small table in terms of number of rows
then 1
when (select 1 from table2 where processflag = 1 and rownum =1) = 1 -- larger than table1 table in terms of number of rows and so on
then 1
..
Else 0 end into processFlag
From dual;
一旦找到一個匹配項, Case when
將停止執行該語句。
您還可以在case when
語句中給出表的順序以獲得更好的性能,在when
子句中先使用小表,然后在末尾使用大表以獲得良好的性能。
干杯!!
你想要這樣的東西嗎?
select . . .
from . . .
where exists (select 1 from table1 where processflag = 1) or
exists (select 1 from table2 where processflag = 1) or
exists (select 1 from table3 where processflag = 1) ;
也就是說,您可以使您的查詢以一堆exists
條件為條件。 如果您使用的是 PL/SQL,您可以使用類似的東西來實際設置一個標志。
您可以使用rownum :
select count(*) into myCounter
from (
select * from Table1 where processflag = 1
) l where rownum = 1;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.