2016-04-13 27 views
1

我有這個疑問:當條件爲false時,是否執行子查詢?

select *, 
    case when p.amount is null then '1' 
      else (select count(1) 
        from Money_paid mp 
       where mp.post_id = p.id and mp.user_id = :user_id limit 1) 
    end paid 
from Posts p 
where p.id = :post_id 

正如你看到的,有在case .. when功能的else部分子查詢。現在我想知道,當p.amount is nulltrue那麼該子查詢執行?


我問,因爲我可以通過PHP代碼實現一個case .. when功能,從我的查詢中刪除它,所以我的查詢將是這樣的:

select *, 
    (select count(1) from Money_paid mp 
     where mp.post_id = p.id and 
       mp.user_id = :user_id and 
       p.amount is not null 
     limit 1) paid 
from Posts p 
where p.id = :post_id 

// and some php code to implement that condition 

總之,如果子查詢針對兩種情況都執行(p.amount is null = truep.amount is null = false),那麼我將使用第二個查詢(不包含case .. when)。但它的子查詢只有執行時,條件是false,然後我會去第一個查詢。

那麼哪一個?

+1

對不起,但你爲什麼不直接嘗試一下呢? –

+0

@low_rents我怎麼能自己弄清楚? – stack

+0

通過在該位置放置更新或插入查詢。 –

回答

1

ELSE將不會執行,除非沒有其他條件爲真。

CASE EXPRESSION正按照您放置的順序逐個評估他的所有情況,因此當第一個條件滿足時,案例就會中斷。

  • 爲例表達式計算爲第一真條件。

  • 如果沒有真實條件,則評估爲ELSE部分。

  • 如果沒有真實條件且沒有ELSE部分,則其評估爲NULL。

+0

因此,子查詢**只**當'p.amount爲null'條件爲'false'時執行,對嗎? – stack

+0

@stack這是正確的 – sagi

+0

如果p.amount很少爲null,那麼它不會有太大的區別,但是如果它有多個空值,'CASE EXPRESSION'將節省大量不必要的選擇。 @stack – sagi

相關問題