2013-05-01 137 views
0

我想從一個表插入數據到另一個,但他們必須通過使用相同的ID鏈接。從一個表插入數據到另一個MYSQL

我使用下面的代碼:

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 - Unknown column 'table1.id' in 'where clause'

我在做什麼錯?

+0

插入不匹配任何東西 - 更新可能 - 所以你可能有兩個想法混合這裏。 – Randy 2013-05-01 20:15:33

回答

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 
+0

我已經試過了,發生的是它會創建新的行。所以它看起來不是表1中的ID是否與表2中的country_code相同 – Daniil 2013-05-01 20:34:38

+0

然後就像Randy說的那樣,您已將'UPDATE'與'INSERT.'混淆。 – imthepitts 2013-05-01 20:39:34

+0

請參閱我更新後從聯接表更新的答案。 – imthepitts 2013-05-01 20:46:50

相關問題