简体   繁体   English

MySQL用父ID替换父名

[英]MySQL replace parent name with parent id

I have a Table (t) like this 我有一个这样的表(t)

t.Name  t.Parent  t.Id
John    Bob       1
Frank   Bob       2
Alice   Frank     3
Tim     John      4
Lucy    Bob       5
Tim     Frank     6
...

Now I want to replace the t.Parent string with the Id of the parent. 现在,我想用父代的ID替换t.Parent字符串。 Is there any way of going about this in MySQL or is the best way to make a little script? 在MySQL中有什么方法可以解决这个问题,或者是编写小脚本的最佳方法吗?

Edit: Thanks All 编辑:谢谢所有

Join the table with itself using the parent name and then do the swap: 使用父名称将表本身与其连接,然后进行交换:

UPDATE table t1 LEFT JOIN table t2 ON t2.Name = t1.Parent
SET t1.Parent = t2.Id

UPDATE: I see I managed to write almost the exact same statement as niktrs. 更新:我看到我设法写了几乎与niktrs相同的语句。 Although I've assumed that you want to swap the values instead of using a new column. 尽管我假设您要交换值而不是使用新列。

Create a column ParentId 创建一列ParentId

Then join the table with itself 然后将桌子与自己连接

UPDATE table t1 JOIN table t2 ON t1.parent = t2.name
SET t1.ParentId = t2.Id

@Brendan has the shortest solution with the joined update. @Brendan是加入更新后的最短解决方案。

Here is a different one with copying the data: 这是复制数据的另一种方法:

CREATE TABLE parents LIKE t;
INSERT INTO parents SELECT * FROM t;
UPDATE t SET parent=(SELECT id FROM parents WHERE name=t.parent ORDER BY id ASC LIMIT 1);

A view could be enough but MySQL refuses to use it in this way. 一个视图可能就足够了,但是MySQL拒绝以这种方式使用它。

After the update ran you can modify the type of the parent field to the same as id has: 运行更新后,您可以将parent字段的类型修改为与id相同:

ALTER TABLE t CHANGE parent parent integer;

And of course you can drop the copy table: 当然,您可以删除副本表:

DROP TABLE parents;

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

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