3

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.

3
  • What do you mean by calculated only once exactly? Commented Jan 27, 2012 at 2:17
  • Why do you care if it is. It will be millions of times faster that actually writing the result to the DB. Commented Jan 27, 2012 at 2:18
  • Well, now it is calculated twice (for every occurrence in the if). I want the n-10 expression to be there just once - in an assignment to a user variable like this: @tmp := n - 10. But I do not know the exact syntax. Commented Jan 27, 2012 at 2:24

2 Answers 2

4

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;
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I was trying to do this exact thing and adding the parentheses is what made it work.
-1

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";

1 Comment

Thank you, but I might have oversimplified my example. In fact, I need to derive the resulting value of n based on other columns in table.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.