简体   繁体   中英

Inserting data from one table into another

There is a one table,

City[city_id,state_id]

There was another table in same database,

Registration[reg_id,city_id]

Now, i have added one more column into 'Registration' table, so it is become as shown below,

    Registration[reg_id,city_id,state_id]

But, the problem is that values of the state_id column is '0'. So, How can i insert value of state_id column of "Registration" table from the "City" table according to matching city_id value of "Registration" table.

This will work in MySQL. In the background it instruct the server to make inner join on two tables.

UPDATE Registration r, City c SET r.state_id = c.state_id WHERE r.city_id = c.city_id;

As long as this query will be performed just once - you could use this not efficient, but readable query:

UPDATE Registration r
   SET state_id = (SELECT state_id
                     FROM City c
                    WHERE c.city_id = r.city_id)

不确定MySQL,但是可以在Oracle和SQL Server中完成:

UPDATE Registration r SET state_id = (SELECT state_id FROM City WHERE city_id = r.city_id)

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