簡體   English   中英

如何在 Oracle SQL 中使用 EXISTS

[英]How to use EXISTS in Oracle SQL

我想通過 stutus=2 獲取所有僅顯示 ID 的記錄,這些 ID 不是 go 但已從特定狀態取消。 表是 A_ORDERS_LOG 和 A_ORDERS。

因此,每個 ID 可以通過各種狀態 go。 我有興趣只查看那些已從某些狀態取消且尚未通過 status=2 的 ID。

我試過這個

SELECT *
  FROM A_ORDERS_LOG
 WHERE ( STATUS1 = 0  AND STATUS2  = 11 )
    OR ( STATUS1 = 1  AND STATUS2  = 11 )
    OR ( STATUS1 = 3  AND STATUS2  = 11 )
    OR ( STATUS1 = 4  AND STATUS2  = 11 )
    OR ( STATUS1 = 41 AND STATUS2  = 11 )
    OR ( STATUS1 = 42 AND STATUS2  = 11 )
    OR ( STATUS1 = 43 AND STATUS2  = 11 )
    OR ( STATUS1 = 5  AND STATUS2  = 11 )
    OR ( STATUS1 = 6  AND STATUS2  = 11 )
   AND EXISTS (
       SELECT STATUS1,
              STATUS2
         FROM A_ORDERS_LOG
        WHERE ( STATUS1 != 2 OR STATUS2 != 2 )
          AND ID IN (
              SELECT ID
                FROM A_ORDERS
       )
)
);

Status2=11 - 表示取消,status1 是取消的狀態。

似乎你需要一個exists和一個not exists ,同時在where子句之后整理過濾狀態:

select *
  from a_orders_log o
 where status1 in ( 0, 1, 3, 4, 5, 6, 41, 42, 43 ) and status2 = 11 
   and not exists (select 0
                     from a_orders_log o3
                    where 2 in ( status1 , status2 ) 
                      and exists ( select 1 from a_orders o2 where o2.id = o3.id ) );

只是通過使用 join 而不是存在來增加更多的簡單性。

select *
  from a_orders_log o
 where status1 in ( 0, 1, 3, 4, 5, 6, 41, 42, 43 ) and status2 = 11 
   and not exists (select 0
                     from a_orders_log aoo join a_orders ao on (ao.id=aoo.id)
                    where 2 in ( status1 , status2 ) )

@barbaros,如果您能檢查它的正確性,我們將不勝感激。

干杯!!

暫無
暫無

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

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