mysql - 如何遍历一个表并根据另一个表中的数据更新字段?
问题描述
我有两张桌子。表_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
解决方案
您不需要循环,您可以使用基于连接的更新
update table2
inner join table1 on table1.id = table2.id
set table2.related_contact = table1.contact_id
推荐阅读
- python - 将年份添加到当前日期
- sql - 在 SQL 中 - 有没有办法按 ID 组合或分组而不按 case 语句分组
- php - PHP循环遍历数组以获取特定值
- sql - 基于尚未匹配的第一个匹配的出现顺序的 SQL 连接
- c++ - 什么是 char (*var)[6] 和 char* var[6]?
- android - Flutter 无法从资产文件夹中检测到“model.tflite”文件(FileNotFoundException)
- database - Kubernetes 上的 etcd 数据库集群行为不端
- c# - 有没有办法重定向到新页面是 System.NullReferenceException 被触发?
- php - 将额外模型附加到 BelongstoMany 关系
- javascript - javascript d3 timeParse utcParse