I am at loss to figure out how to do an UPDATE with CASE and JOIN. This example is from my Drupal database. content_type has nid as its primary key; term_node, on the other hand, can have multiple rows with the same nid matched to different tids. MySQL will happily parse a query based on WHERE:
UPDATE `content_type`
LEFT JOIN `term_node` USING(nid)
SET
`field_m03` = 1
WHERE tid = 696;
The above updates all rows in content_type which have an nid matched to (tid = 696) in term_node, as it should.
But when I try to string several conditions with CASE it won’t work. No errors, but 0 rows affected:
UPDATE `content_type`
LEFT JOIN `term_node` USING(nid)
SET
`field_m03` = (CASE
WHEN (tid = '696') THEN '1'
WHEN (tid = '697') THEN '2'
WHEN (tid = '698') THEN '3'
WHEN (tid = '699') THEN '4'
WHEN (tid = '700') THEN '5'
ELSE `field_m03`
END);
Also tried without the parentheses and single quotes, no change.
Your syntax seems correct.
If your MySQL server has safe updates (SQL_SAFE_UPDATES) turned on, then your server will abort any updates that don’t have a
WHEREorLIMITclause.