Can someone show me the correct mysql syntax to do the following:
Update a column in a table with 1 of 3 values:
If col_A = 4 set col_Z to col_A If col_B = 4 set col_Z to col_B Else set col_Z to NULL (or leave alone because col_Z is initialized to NULL)
Here's what I have:
Update my_table
SET col_Z = IF(col_A = 4, col_A, IF(col_B = 4, col_B, NULL))
WHERE id = "001"
IS this correct?
Answer: MySQL IF() function can be used within a query, while the IF-ELSE conditional statement construct is supported to be used through FUNCTIONS or STORED PROCEDURES.
SET is a data type of String object that can hold zero or more, or any number of string values. They must be chosen from a predefined list of values specified during table creation. It is one of the rarely used data type in the MySQL database.
Yes, it looks correct.
The following code will be simpler though.
UPDATE my_table
SET col_Z = IF(col_A = 4 OR col_B = 4, 4, NULL)
WHERE id = "001"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With