首页 > 解决方案 > 如何遍历一个表并根据另一个表中的数据更新字段?

问题描述

我有两张桌子。表_1 和表_2。table_1 包含几列,但我需要的两列是 table_1.id 和 table_1.contact_id。table_2 包含一个空白列 table_2.related_contact 和一个填入 table_2.cid 的列。table_2.cid 和 table_1.id 是一样的。

我想根据 table_2.cid 循环 table_2 和其中 table_2.cid = table_1.id 更新 table_2.related_contact 与同一行的 table_1.contact_id 的值。

我的 SQL 知识还可以,但这超出了我的范围。我查看了其他答案,但找不到适合此示例的答案。

循环前示例:

表格1

id: 3745        contact_id: ae456-78ef
Id: 3746        contact_id: oi958=34hb

表 2

cid:3745         related_contact: NULL
cid:3746         related_contact: NULL

循环后:

表 2

cid: 3745         related_contact: ae456-78ef
cid: 3746         related_contact: oi958=34hb

标签: mysql

解决方案


您不需要循环,您可以使用基于连接的更新

update table2 
inner join table1 on table1.id = table2.id 
set table2.related_contact = table1.contact_id 

推荐阅读