【问题标题】:MYSQL inserting data from one table into the otherMYSQL将数据从一个表插入另一个表
【发布时间】:2013-04-25 21:32:04
【问题描述】:

我正在尝试将数据从一个表插入到另一个表中,但它们必须使用相同的 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'

我做错了什么?

【问题讨论】:

  • inserts 不匹配任何东西 - UPDATES 可能 - 所以你可能在这里混合了两个想法。

标签: mysql select insert where-clause


【解决方案1】:

试试这个:

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 

【讨论】:

  • 我试过了,结果是它创建了新行。所以不看table1中的id是否和table2中的country_code一样
  • 那么就像 Randy 说的,你把 UPDATEINSERT. 混淆了
  • 请查看我的更新答案以从连接表进行更新。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-05
  • 2018-04-05
  • 1970-01-01
  • 1970-01-01
  • 2014-08-12
相关资源
最近更新 更多