简体   繁体   English

将数据从一个表插入另一个表

[英]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'. 但是,问题在于state_id列的值为'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. 因此,如何根据“注册”表的匹配city_id值从“城市”表中插入“注册”表的state_id列的值。

This will work in MySQL. 这将在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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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