简体   繁体   中英

Copy from one table to another table

I know how to copy from one table to another table using MySQL:

INSERT INTO original_table
SELECT * FROM temp_table WHERE id = 1

But my situation is different:

I have temp_table and original_table . Both having same column name ie,

    id,
    state,
    city,
    address

But temp_table contains real name of state and city ie, state and city column contain name of state and city. AND I want to copy this table such way that state and city should contain id of that states and city name when it move to original_table . There is meta table for both states and cites.

states :

id 
state_name

cities :

id,
state_id,
city_name

How can I achieve this?

Just join your temp_table to the states and cities tables appropriately:

INSERT INTO original_table
  (id, state, city, address)
SELECT t.id, s.id, c.id, t.address
FROM   temp_table t
  JOIN states     s ON s.state_name = t.state
  JOIN cities     c ON c.city_name  = t.city

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