简体   繁体   中英

MYSQL inserting data from one table into the other

I am trying to insert data from one table into the other one, but they have to link by using the same ID.

I use the following code:

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

And I am getting the following error:

#1054 - Unknown column 'table1.id' in 'where clause'

What am I doing wrong?

Try this:

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 

This will pull the country code from the source table and insert it as the ID in the new table. Thus, they will be "linked" by the same ID.

If you're trying to update existing rows that match the country code, you'll need to do this:

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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM