user variables in mysql update statement
-
19-04-2021 - |
سؤال
Let t
be a mysql table and n
be an integer column in it. I would be interested if the following query can be modified so that the expression n - 10
is calculated only once.
UPDATE t SET n = if(n - 10 < 1, 1, n - 10) WHERE n = 5;
The query does not make sense, I know, but I need to use the same pattern in the real application where values 10
and 5
would be php variables.
المحلول
Allright, i have finally found the right syntax. The parentheses around @tmp := n - 10
are crucial.
UPDATE t SET n = if((@tmp := n - 10) < 1, 1, @tmp) WHERE n = 5;
نصائح أخرى
You can just do such logic in php:
$value = $n - 10;
$value = $value < 1 ? 1 : $value;
$sql = "UPDATE t SET n = $value WHERE n = $n";
لا تنتمي إلى StackOverflow