【发布时间】:2021-09-28 06:04:29
【问题描述】:
我有两个如下表(数据库 MYSQL):
Table1
id
col1
Table2
id
col1 -> foreign key(Table1 - id)
col2
现在我想将具有以下条件的所有行的值插入 Table2(col2):
从 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
我尝试使用 select join 和 where 插入,但显然无法正常工作
insert into Table2(col2)
select t1.col1 from Table1 t1 join Table2 t2 on t1.id = t2.col1
任何指针?
更新
搞定了。感谢@rahul @frank 的指点,我实际上需要更新
update Table2 t2
set col2 = (SELECT t1.col1 FROM Table1 t1 where t1.id = t2.col1);
【问题讨论】:
-
需要更新而不是插入
-
一个 INSERT 添加了附加行。你想要的是一个 UPDATE (它改变 existing 行的 column 值)。
-
感谢@FrankSchmitt 的指点