mysql - INSERT into Mysql table from table2, comparing variables in both tables
问题描述
Ok, I have two tables, Region and Cities and I need to link them together using the id from regions. At present a common code is used which does not work for my use case.
Region Table:
+--------------+--------------+------+-----+---------+----------------+
| 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 | |
+--------------+--------------+------+-----+---------+----------------+
City Table
+--------------+------------------+------+-----+---------+----------------+
| 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 | |
+--------------+------------------+------+-----+---------+----------------+
In the City table, I have added the int region_id and I would like to populate it from the region table based on some city.country_code = region.country_code AND region.code = city.state.
Something along these lines:
INSERT INTO city (region_id) SELECT id FROM region WHERE city.country_code = region.country_code AND city.state = region.code;
That's the essence of what I am trying to do, MySql work is not a strong point.
Any help, appreciated!
解决方案
我认为您想要一个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
推荐阅读
- php - 如何在php中增加会话时间
- counter - Add() 在 Java 中不起作用(Greenfoot)
- javascript - HTML5 File API - 使用 PHP 将 blob 保存到文件
- javascript - JavaScript 中的井字游戏获胜条件
- .net - Incapsula 阻止包含危险标签的 HTML 上传文件
- ios - 更改语言后如何强制用户重新启动应用程序
- assembly - 汇编任务:翻译
- python - 如何在 django 中实现多级管理?
- python - 在 Jupyter Lab 笔记本中使用 PyMongo 不会关闭与 MongoDB 服务器的任何连接
- html - 在浮动 div 周围环绕文本(和图像)