我有 2 个更新查询要合并为一个查询。有办法做到这一点吗?
查询 1:
update user_meta set
meta_value = case meta_key
when 'mobile' then '{$mobile}'
when 'interest' then '{$interest}'
when 'occupation' then '$occupation'
when 'address' then '{$address}'
when 'city' then '{$city}'
when 'country' then '{$country}'
when 'about' then '{$about}'
when 'website' then '{$website}'
else meta_value
end
where userid = {$id}
其他查询:
update user set fullname='{$fullname}' where userid={$id}
这两个查询是在同一个函数中同时执行的,但是有不同的表。另外,这样我必须运行两个更新查询。
如果我想将这个 when 语句放入循环中怎么办?如果要更新 100 个值,将非常困难。
最佳答案
可以在一条语句中更新多个表。
例如:
UPDATE user u
JOIN user_meta m
ON m.userid = u.userid
SET m.meta_value = CASE m.meta_key
WHEN 'mobile' THEN '{$mobile}'
WHEN 'interest' THEN '{$interest}'
WHEN 'occupation' THEN '{$occupation}'
WHEN 'address' THEN '{$address}'
WHEN 'city' THEN '{$city}'
WHEN 'country' THEN '{$country}'
WHEN 'about' THEN '{$about}'
WHEN 'website' THEN '{$website}'
ELSE m.meta_value
END
, u.fullname = '{$fullname}'
WHERE u.userid = {$id}
关于php - 在 MySQL 中将 2 个更新查询作为一个运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21166967/