如何插入与两个表中的 id 匹配的列?

How to insert a column that matches id from both tables?

我有 2 tables,用户和等级。 用户看起来像这样:

ID | Name | Area
1  | John | Hub

这样的成绩:

ID | ID_from | ID_for | G1 | G2 | Area
1  |   23    |    22  |  9 | 8  |  NULL

我想将用户 table 的区域插入成绩 table,其中 users.id = grades.ID_for

我已经试过了

INSERT INTO grades
SELECT area FROM users
where ID_for = users.id;

但我得到“#1054 - Champ 'ID_for' inconnu dans where 子句”。

区域 table 需要提供的值数量为 6(即 ID | ID_from | ID_for | G1 | G2 | Area)。但您只提供了 3 个(ID | 姓名 | 区域)

您需要将所有列从源 table 映射到目标 table。

而且,您似乎正在尝试更新区域而不是插入区域。如果是的话

update grades 
set Area = (select area from users where users.id = grades.ID_for) 

可能会完成这项工作。如果您打算仅更新空值的区域,则

update grades 
set Area = (select area from users where users.id = grades.ID_for) 
where area is null