Php 如果ELSE条件在更新查询中不起作用

Php 如果ELSE条件在更新查询中不起作用,php,Php,我想使用if-else条件基于一列值更新两列。 如果col1为空,则通过添加随机数更新col2。 否则,通过添加随机数来更新col1 我尝试这种方式,但得到语法错误 $query = "UPDATE table SET IF(col1='', col2=col2+FLOOR($min+(RAND()*($max-$min+1))), col1=col1+FLOOR($min+(RAND()*($max-$min+1)))) WHERE id >= $id"; 请查看并建议任何可能的方法。

我想使用if-else条件基于一列值更新两列。 如果col1为空,则通过添加随机数更新col2。 否则,通过添加随机数来更新col1

我尝试这种方式,但得到语法错误

$query = "UPDATE table SET IF(col1='', col2=col2+FLOOR($min+(RAND()*($max-$min+1))), col1=col1+FLOOR($min+(RAND()*($max-$min+1)))) WHERE id >= $id";
请查看并建议任何可能的方法。
感谢您对MySQL中的
IF()
的理解有点错误:它是一个控制流函数,而不是一个构造

这意味着,不是控制更新哪个列,而是控制写入哪个值

因此,您需要以某种方式重新组合,
SET
的列保持不变,同时使值变为变量。如果不满足此列的条件,我们只需重新指定旧值即可实现这一点

UPDATE table SET 
  col2=IF(col1='', col2+FLOOR($min+(RAND()*($max-$min+1))), col2),
  col1=IF(col1='', col1, col1+FLOOR($min+(RAND()*($max-$min+1)))) 
WHERE id >= $id
编辑

从注释中可以看出:如果要在col1上选择另一个空字符串null,则必须为其选择:

UPDATE table SET 
  col2=IF(col1='' OR col1 IS NULL, col2+FLOOR($min+(RAND()*($max-$min+1))), col2),
  col1=IF(col1='' OR col1 IS NULL, col1, col1+FLOOR($min+(RAND()*($max-$min+1)))) 
WHERE id >= $id
编辑2

如果col2不仅可以是空字符串,还可以是null,则需要再次测试:

UPDATE table SET 
  col2=IF(col1='' OR col1 IS NULL, IFNULL(col2,0)+FLOOR($min+(RAND()*($max-$min+1))), col2),
  col1=IF(col1='' OR col1 IS NULL, col1, col1+FLOOR($min+(RAND()*($max-$min+1)))) 
WHERE id >= $id

查询正在运行,但问题是它在更新时不工作,有时即使col1为null也不工作。空字符串和null之间有一个主要区别-一个是通过
col1='
选择的,另一个是通过
col1为null
选择的!仍然不处理col2 null值,仅当col2有值时才处理。不处理col1有值或为null。没有测试col2是否为null,并且OQ中也没有测试。如果col2可以为null,则需要对其进行测试。。。查看编辑只要while循环运行,我就会多次执行相同的查询,而不是只运行一次。是的,我在这里使用while循环,因为您使用了“WHERE id>=$id”,这意味着您有多行(id大于$id)。所以我把循环放到循环中,一行一行地获取数据,然后在循环中一行一行地更新它们……这样做可以奏效,但在有很多行的情况下,这不是最好的方法,如果您能提供帮助,我正在寻找单一查询方法。好的,谢谢您告诉我这在您的系统上工作,我也在为您查找查询…但这也是我更新数据的好方法。。。!!!我并没有像你们发布的那个样测试你们的方法,我自己尝试过这种方法,直到更新花费了相当长的时间,然后我使用了单查询方法,只花了几秒钟,但当我不得不基于另一个列值更新时,问题就出现了。
//hi i just try this logic on my "mysql" may be it work on your system....
//plz take a llok to the logic i try


//i don't know about the case condition but i try to help and check that is it working on your function..


//here i select the whole table row with true condition 
//here i have single row which set true condition
$q = "select * from table where id>=".$id;
$r = mysql_query($q);


//i take one row at a time with ture contition and update values by checking column is empty or not 
//this llop run till the values are there  with true condition in select query
while($ro = mysql_fetch_array($r)){

//for every row in loop i check the condition that col1 is empty, if it is then i update col 2
if($ro['col1']==""){
$q_update = "update table set col2=".$rand." where id>=".$ro['id'];
$r_update = mysql_query($q_update);
}
//for every row in loop i check the condition that col1 is empty, if it is not then i update col1
else{
$q_update = "update table set col1=".$rand." where id>=".$ro['id'];
$r_update = mysql_query($q_update);
}


}//while loop ends here