MySql通过查询结果集更新数据

12次阅读

共计 917 个字符,预计需要花费 3 分钟才能阅读完成。

表结构
现在有用户表和用户实名认证表,user_info,user_card。
user_info 中的字段有 user_id,user_name。
user_card 中的字段有 user_id,user_card,user_name。
其中 user_name 为用户实名认证的信息,user_info 中做了字段冗余。

问题
用户表 user_info 中的 user_name 和 user_card 中的 user_name 不同步。
user_card 中有值,user_info 中没有值。
需要将 user_card 中的 user_name 同步到 user_info 中去。

解决方法
1. 通过代码查询出 user_info 中 user_name 为空的数据 , 然后通过 user_id 查询出用户实名认证的数据进行同步。
select user_id from user_info where user_name = ” ;

select * from user_card where user_id in (上面的结果集) ;

通过代码更新数据
2. 联表查询后更新数据
SELECT
c.user_id ,
c.user_name
FROM
user_info AS u
LEFT JOIN user_card AS c ON u.user_id = c.user_id
WHERE
u.user_name = ”;

通过代码更新数据
3. 通过 MySql 内联更新数据
先写出更新语句
UPDATE `user_info` as u SET u.user_name = ‘ 结果集 ’ ;

再获取条件结果集
SELECT
c.user_id ,
c.user_name
FROM
user_info AS u
LEFT JOIN user_card AS c ON u.user_id = c.user_id
WHERE
u.user_name = ”;

最后内联更新
UPDATE `user_info` as u
INNER JOIN
(
SELECT
c.user_id ,
c.user_name
FROM
user_info AS u
LEFT JOIN user_card AS c ON u.user_id = c.user_id
WHERE
u.user_name = ”;
) as r ON u.user_id = r.user_id SET u.user_name = r.user_name ;

正文完
 0