2013-04-27 85 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

相关问题