[英]Insert value into column in new table based on value from another column
我有以下兩個表:
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
我想根據名稱將表 1 中的正確 table1_id 添加到表 2 的 table1_id 列中。 所以第一行是 1 - 1 - 湯姆,等等。
這如何在 MySQL 查詢中執行?
感謝幫助!
您可以使用join
:
update table2 t2 join
table1 t1
on t2.name = t1.name
set t2.table1_id = t1.table1_id;
為了提高性能,您需要在table1(name)
上建立索引。 您還希望確保該列在table1
沒有重復。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.