我想使用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";
请参阅并建议任何可行的方法。 感谢
答案 0 :(得分:1)
您对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上选择 etiher 空字符串或 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
答案 1 :(得分:-1)
//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