[英]INSERT into Mysql table from table2, comparing variables in both tables
好的,我有两个表,Region 和 Cities,我需要使用区域中的 id 将它们链接在一起。 目前使用的通用代码不适用于我的用例。
区域表:
+--------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| country_code | varchar(255) | NO | MUL | NULL | |
| code | varchar(255) | NO | | NULL | |
| name | varchar(255) | NO | | NULL | |
+--------------+--------------+------+-----+---------+----------------+
城市表
+--------------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------------+------------------+------+-----+---------+----------------+
| id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| country_code | varchar(255) | NO | MUL | NULL | |
| name | varchar(255) | NO | | NULL | |
| state | varchar(255) | NO | | NULL | |
| ascii_name | varchar(255) | NO | | NULL | |
| latitude | double | NO | | 0 | |
| longitude | double | NO | | 0 | |
| timezoneid | varchar(255) | NO | | NULL | |
| region_id | int(11) | YES | | NULL | |
+--------------+------------------+------+-----+---------+----------------+
在 City 表中,我添加了 int region_id,我想根据一些 city.country_code = region.country_code AND region.code = city.state 从区域表中填充它。
这些方面的东西:
INSERT INTO city (region_id) SELECT id FROM region WHERE city.country_code = region.country_code AND city.state = region.code;
这就是我想要做的事情的本质,MySql 工作并不是一个强项。
任何帮助,不胜感激!
我认为您想要一个update
语句(修改现有行上的数据)而不是insert
(创建新行)。
如果是这样,您可以使用 MySQL 的update... join
语法:
update city c
inner join region r
on c.country_code = r.country_code
and c.state = r.code
set c.region_id = r.id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.