0

我回答了以下问题问题链接。但我发现 stringe 行为。当我写这个

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

在其他情况下它给出 null 我不明白为什么当我使用 Max 它给出 null 为什么?

4

2 回答 2

1

不同之处在于,count对于空结果返回零,但max对于空结果返回 null。

product.ID <product.id在子查询中有您的条件,当您将字段与其自身进行比较时,这将始终为假。这将使子查询的结果为空。

应该是b.ID <product.id将子查询中表中的值与外部查询中表中的值进行比较。

因此,这两个查询都没有按预期工作,但是当您使用时,count您不会从空结果中获得空值。

于 2013-04-27T06:38:56.583 回答
0

你可以试试这个(对于mysql):

select ifnull(max(column), 0)   when max() return null, it give you 0.
于 2013-04-27T06:59:31.637 回答