开发者

MySQL replace parent name with parent id

I have a Table (t) like this

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 wi开发者_JAVA百科th the Id of the parent. Is there any way of going about this in MySQL or is the best way to make a little script?

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. Although I've assumed that you want to swap the values instead of using a new column.


Create a column 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.

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.

After the update ran you can modify the type of the parent field to the same as id has:

ALTER TABLE t CHANGE parent parent integer;

And of course you can drop the copy table:

DROP TABLE parents;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜