[英]update values of table based on foreign key
I've two tables like below (database MYSQL):我有如下两个表(数据库 MYSQL):
Table1
id
col1
Table2
id
col1 -> foreign key(Table1 - id)
col2
Now I want to insert value into Table2(col2) for all rows with the following condition:现在我想将具有以下条件的所有行的值插入到 Table2(col2) 中:
Get value from Table1(col1) where Table2(col1) = Table1(id)从 Table1(col1) 中获取值,其中 Table2(col1) = Table1(id)
Example:
Before Insert:
Table1
id col1
1 value1
2 value2
Table2
id col1(fk) col2
3 1 NULL
4 2 NULL
After Insert:
Table2
id col1(fk) col2
3 1 value1
4 2 value2
I tried insert into with select join and where but apparently couldn't get it to work我尝试使用 select join 和 where 插入,但显然无法正常工作
insert into Table2(col2)
select t1.col1 from Table1 t1 join Table2 t2 on t1.id = t2.col1
Any pointers?任何指针?
Update更新
Got it working.得到它的工作。 Thanks for the pointers @rahul @frank I actually need to do update感谢指点@rahul @frank 我真的需要做更新
update Table2 t2
set col2 = (SELECT t1.col1 FROM Table1 t1 where t1.id = t2.col1);
Update with JOIN使用 JOIN 更新
-- MySQL
UPDATE Table2
INNER JOIN Table1
ON Table2.col1 = Table1.id
SET Table2.col2 = Table1.col1;
Please check from url https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=a28fec2da45aa634f2509ec9299c2bed请从 url https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=a28fec2da45aa634f2509ec9299c2bed 查看
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.