简体   繁体   English

将ID从一个表插入到另一个基于另一列的表

[英]Insert id's from one table to another based on another column

New MySql user here. 新的MySql用户在这里。

Suppose I have two tables: 假设我有两个表:

Table1 rownames -> external_id, name, location 表1行名-> external_id,名称,位置

Table2 rownames -> id, name, type, value, year Table2行名-> ID,名称,类型,值,年份

What I want to do is to write a script where it populates in Table2.id the value from Table1.external_id, if there is a match in Table1.name and Table2.name. 我想做的是编写一个脚本,如果Table1.name和Table2.name中存在匹配项,那么它将在Table2.id中填充Table1.external_id中的值。

I thought about something like this, but unfortunately its not working. 我曾想过类似的事情,但不幸的是它没有用。

insert into Table2.id
    select Table1.external_id
    where Table1.name = Table2.name

try this: 尝试这个:

insert into Table2 (id)
    select Table1.external_id
    where Table1.name = Table2.name;

If you do an insert here, what you will do is create a whole bunch of duplicates. 如果您在此处进行插入,则要做的就是创建一堆重复项。 What you need is an update join 您需要的是一个更新联接

UPDATE table1 INNER JOIN table2 set table2.id = table1.external_id
WHERE Table1.name = Table2.name;

You don't need any script for this, just type this into the mysql client, phpmyadmin etc 您不需要任何脚本,只需将其键入mysql客户端,phpmyadmin等

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

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