2013-04-27 59 views
0

我回答了以下問題question link。但我付出嚴厲的行爲。 當我寫這篇文章爲什麼當我使用max而不是count時出現問題

Update product Set [order]= Case when Not Exists (Select * from 
product a where a.ProductTypeID =product.ProductTypeID and a.id 
<product.ID) 
    tHEN 1 
    eLSE 
    ((Select cOUNT([ORDER])+1 from product b where 
    b.ProductTypeID =product.ProductTypeID and product.ID <product.id)+1) 
    eND 

它運作良好,但是當我寫的......」

Update product Set [order]= Case when Not Exists (Select * from 
    product a where a.ProductTypeID =product.ProductTypeID and a.id 
    <product.ID) 
     tHEN 1 
     eLSE 
     ((Select Max([ORDER])+1 from product b where 
     b.ProductTypeID =product.ProductTypeID and product.ID <product.id)+1) 
     eND 

這是在給別人的情況我不明白爲什麼無效?誰能解釋這時候我丟失的原因當我使用Max.Here是sql提琴http://sqlfiddle.com/#!3/1e15d/1我在哪裏使用計數當我使用最大它給null爲什麼?

+0

但如果我申請兩個reutrn INT爲int的列看到問題.....鏈接當我使用指望它工作,但是當我使用最多它返回null不會... – 2013-04-27 06:26:31

+0

沒有它沒有....它當我使用計數詮釋它的作品,但是當我使用Max代替計數它給null ...爲什麼是... lyk那...] – 2013-04-27 06:28:38

+0

我只是wana知道爲什麼它會給出null當我在上面使用Max時... sql語句 – 2013-04-27 06:30:22

回答

1

區別在於count對於空結果返回零,但max對於空結果返回null。

在子查詢中,您的條件中有product.ID <product.id,因爲您將字段與自身進行比較時該字段始終爲假。這將使子查詢的結果爲空。

它應該是b.ID <product.id將子查詢中的表中的值與外部查詢中的表中的值進行比較。

因此,這兩個查詢都無法按預期工作,但是當您使用count時,您不會從空結果中獲得空值。

+0

謝謝@guffa ....多數民衆贊成什麼我wana知道什麼即時通訊失蹤感謝很多..... – 2013-04-27 06:42:04

0

你可以試試這個(爲MySQL):

select ifnull(max(column), 0) when max() return null, it give you 0. 
+0

我沒有空我的表朋友 – 2013-04-27 07:00:05

+0

無論如何感謝您的回覆.... – 2013-04-27 07:01:50

相關問題