如何使用 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中文網其他相關文章!