在 MySQL 中,可以通过关联更新(UPDATE JOIN)基于一个表的数据更新另一个表的字段,这在需要根据关联条件同步数据时非常实用。
UPDATE 表1
JOIN 表2 ON 表1.关联字段 = 表2.关联字段
SET 表1.字段1 = 表2.字段1,
表1.字段2 = 表2.字段2 + 100
[WHERE 条件];
假设有两个表:
-
users 表:存储用户基本信息(id, name, city)
-
user_profiles 表:存储用户详细信息(user_id, address, city)
现在需要根据 user_profiles 表的 city 字段更新 users 表的 city 字段:
UPDATE users
JOIN user_profiles ON users.id = user_profiles.user_id
SET users.city = user_profiles.city
WHERE user_profiles.city IS NOT NULL;
也可以关联多个表进行更新:
UPDATE orders o
JOIN users u ON o.user_id = u.id
JOIN regions r ON u.region_id = r.id
SET o.shipping_fee = r.base_fee * 1.1
WHERE r.country = 'China';
-
关联条件(ON 子句)必须明确,否则可能导致全表更新
-
建议先使用 SELECT 语句验证关联结果:
SELECT users.id, users.city, user_profiles.city
FROM users
JOIN user_profiles ON users.id = user_profiles.user_id
WHERE user_profiles.city IS NOT NULL;
-
可以使用 LEFT JOIN 确保即使右表无匹配也能更新(此时右表字段为 NULL)
关联更新是处理表间数据同步的高效方式,比逐条更新更节省资源。