如何使用 CASE 有效更新 MySQL 中的条目以获得新值
如何使用 CASE 语句更新 MySQL 中的条目以获得新值值,请遵循这些步骤:
UPDATE table_name SET column_name = CASE WHEN condition1 THEN value1 WHEN condition2 THEN value2 ... ELSE valueN END
UPDATE ae44 SET price = CASE WHEN ID = 'AT259793380' THEN '500' WHEN ID = 'AT271729590' THEN '600' WHEN ID = 'AT275981020' THEN '700' ELSE NULL -- Optional: Set values for the remaining matching ID values END
注:问题提供的查询将具有其他 ID 的记录的价格更新为 NULL。要避免这种情况:
选项 1:指定默认值:
UPDATE ae44 SET price = CASE WHEN ID IN ('AT259793380', 'AT271729590', 'AT275981020') THEN CASE WHEN ID = 'AT259793380' THEN '500' WHEN ID = 'AT271729590' THEN '600' WHEN ID = 'AT275981020' THEN '700' END ELSE price END
选项 2:使用 JOIN:
UPDATE ae44 JOIN ( SELECT 'AT259793380' AS oldval, '500' AS newval UNION ALL SELECT 'AT271729590' AS oldval, '600' AS newval UNION ALL SELECT 'AT275981020' AS oldval, '700' AS newval ) q ON ae44.id = q.oldval SET price = q.newval
以上是如何使用 CASE 进行动态赋值来更新 MySQL 条目?的详细内容。更多信息请关注PHP中文网其他相关文章!