[英]Insert value into column in new table based on value from another column
I have the following two tables:我有以下两个表:
table 1:
------------------
table1_id name
------------------
1 tom
2 bob
3 anne
table 2:
------------------------------------
table2_id table1_id name
------------------------------------
1 tom
2 tom
3 anne
4 tom
5 bob
6 bob
7 anne
8 tom
I want to add the correct table1_id from table 1 into the table1_id column of table 2 based on the name.我想根据名称将表 1 中的正确 table1_id 添加到表 2 的 table1_id 列中。 So that the first row is 1 - 1 - tom, ect.
所以第一行是 1 - 1 - 汤姆,等等。
How can this be executed in a MySQL query?这如何在 MySQL 查询中执行?
Thanks for help!感谢帮助!
You can use join
:您可以使用
join
:
update table2 t2 join
table1 t1
on t2.name = t1.name
set t2.table1_id = t1.table1_id;
For performance, you want an index on table1(name)
.为了提高性能,您需要在
table1(name)
上建立索引。 You also want to be sure that the column is not duplicated in table1
.您还希望确保该列在
table1
没有重复。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.