I have a problem on how can I update multiple in mysql in just one query the flow here is just like these.
This will work and runs correctly
UPDATE table SET date_1 = Null WHERE '0000-00-00' = DATE_FORMAT(table_column1,'%Y-%m-%d') UPDATE table SET date_2 = Null WHERE '0000-00-00' = DATE_FORMAT(table_column2,'%Y-%m-%d') UPDATE table SET date_3 = Null WHERE '0000-00-00' = DATE_FORMAT(table_column3,'%Y-%m-%d')
What I’ve tried
UPDATE table SET date1= NULL, date2= NULL, date3= NULL WHERE '0000-00-00' = DATE_FORMAT(table_column1,'%Y-%m-%d') OR '0000-00-00' = DATE_FORMAT(table_column2,'%Y-%m-%d') OR '0000-00-00' = DATE_FORMAT(table_column3,'%Y-%m-%d')
But the problem, it update all of my records into null even if the value of each column is not equal to 0000-00-00
since I’ve been using OR
statement. It would be great if anybody could figure out, thank you so much in advance!.
Advertisement
Answer
UPDATE table SET date_1 = CASE WHEN '0000-00-00' = DATE_FORMAT(table_column1,'%Y-%m-%d') THEN NULL ELSE date_1 END, date_2 = CASE WHEN '0000-00-00' = DATE_FORMAT(table_column2,'%Y-%m-%d') THEN NULL ELSE date_2 END, date_3 = CASE WHEN '0000-00-00' = DATE_FORMAT(table_column3,'%Y-%m-%d') THEN NULL ELSE date_3 END;
PS. WHERE conditions are copied as-is.
PPS. I recommend to add WHERE clause which ensures that at least one column from table_columnX ones contains zero date also.