【问题标题】:INSERT into Mysql table from table2, comparing variables in both tables从table2插入Mysql表,比较两个表中的变量
【发布时间】:2020-10-07 20:57:36
【问题描述】:

好的,我有两张表,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 工作并不是一个强项。

任何帮助,不胜感激!

【问题讨论】:

    标签: mysql sql join select sql-update


    【解决方案1】:

    我认为您需要 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
    

    【讨论】:

    • 谢谢,这为我节省了很多时间!处理了 300 万行。
    猜你喜欢
    • 1970-01-01
    • 2012-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-28
    • 2013-03-03
    • 1970-01-01
    • 2019-12-26
    相关资源
    最近更新 更多