2012-03-15 82 views
0

我在我的数据库中有这张表,每次需要加1。除非它是空的,我想将它设置为1。我想过让默认值为零,但我也需要零。检查为空或不是

例如

----------------------- 
id  number 
----------------------- 
01  NULL 
02  3 
03  1 

我不想跑2个查询。

QUERY1 : SELECT number and store it in variable 

if($number == NULL) $number = 1 
else 
{ 
$number = $number++ 
} 

QUERY2 : UPDATE number 

是否有任何1 SQL查询可以做到这一点,我没有处理的数据在PHP?

感谢的

回答

3
UPDATE table SET number=IF(number IS NULL,1,number+1) 

这应该做的伎俩。

0

是的,您可以检测值是否为NULL。这样做:

UPDATE mytable SET number = IF(ISNULL(number), 1, number+1) 

这将设置任何号码,不要NULL为1,由一个增加了其它号码。所以这个:

----------------------- 
id  number 
----------------------- 
01  NULL 
02  3 
03  1 

将产生:

----------------------- 
id  number 
----------------------- 
01  1 
02  4 
03  2 

这样,你不必去通过PHP了。

+0

非常感谢你.. – 2012-03-15 09:57:42