我试图将数据从一个表插入另一个表,但是它们必须使用相同的ID进行链接。

我使用以下代码:

INSERT INTO table1 (population_total, GDP_current_US, life_expectancy_at_birth)
SELECT population_total, GDP_current_US, life_expectancy_at_birth
FROM table2
WHERE table1.id=table2.country_code


我收到以下错误:


  #1054-“ where子句”中的未知列“ table1.id”


我究竟做错了什么?

最佳答案

尝试这个:

INSERT INTO table1 (id, population_total, GDP_current_US, life_expectancy_at_birth)
SELECT country_code, population_total, GDP_current_US, life_expectancy_at_birth
FROM table2


这将从源表中提取国家代码,并将其作为ID插入新表中。因此,它们将通过相同的ID“链接”。

如果您要更新与国家/地区代码匹配的现有行,则需要执行以下操作:

UPDATE table1
JOIN table2
    ON table1.id = table2.country_code
SET
    population_total = table2.population_total,
    GDP_current_US = table2.GDP_current_US,
    life_expectancy_at_birth = table2.life_expectancy_at_birth

关于mysql - MYSQL将数据从一个表插入另一个表,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16325709/

10-11 22:25
查看更多