MySQL: Update only if certain value in field before
Question by GoldStock | 2012-09-08 at 15:28
I have a little problem with a database query in MySQL. I want to change a value in one field with an UPDATE command. However, a change should only be carried, if there is a specific value stored in the field before. Otherwise, the old value should be kept.
Example: I want to set the field "foo" in the table "users" to 3 where the id = 10, but only when the field was previously set to 2. Otherwise, the field should keep the previous value, because the values should only become bigger and not smaller.
Related Topics
MySQL: Write current Date or Time into Column
Tutorial | 0 Comments
Send Form Input as an Array to PHP Script
Tip | 0 Comments
How to Replace multiple Texts at the same Time
Tutorial | 0 Comments
How to resize Image before Upload in Browser
Tutorial | 13 Comments
HTML: Preassign HTML Form with Data
Tutorial | 0 Comments
Color Values: Convert RGB, CMYK, CMY, HSV, TColor and XYZ Values
Tutorial | 0 Comments
MySQL: How many records have been found or are affected by my query?
Info | 0 Comments
Important Note
Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.
Participate
Ask your own question or write your own article on askingbox.com. That’s how it’s done.
You can use if-statements in MySQL, in order to manage a case. To take your example:
Behind the 'foo =', there is such an IF statement. If 'foo = 2', the first option after the first comma is used (the 3 is written in the field). If 'foo = 2', the second alternative behind the second comma is taken. That is foo, and thus the old value of the field remains. It is important to mention this extra, otherwise afterwards there will be no value in the field.
You also wrote, "the values should only become bigger and not smaller" Perhaps, therefore, also this statement could be interesting for you:
With this, foo is set to 3, if foo was smaller than 3 previously. So, foo also will be set to 3, if there was a 0 or a 1 in the field before, not only if there was a 2.
2012-09-10 at 20:48