简体   繁体   English

使用自引用列更新 MySQL 表

[英]Updating a MySQL table with a self-referencing column

I have a table (simplified) that looks like this:我有一个看起来像这样的表(简化):

id     | name   | selfreference | selfreference-name
------ | -------| --------------| ------------------ 
1      | Vienna |               |  
2      | Wien   |               | Vienna
3      | Виена  |               | Vienna

The selfreference column refers to the id numbers of the same table. selfreference 列指的是同一个表的 id 号。 In the above example, both Wien and Виена refer to the same city, so the value of their selfreference column should be equal to 1.在上面的例子中,Wien 和 Виена 都指的是同一个城市,所以他们的 selfreference 列的值应该等于 1。

In other words, I need to do something like换句话说,我需要做类似的事情

 update `places` 
 set `places`.`selfreference` = 
 (select `places`.`id` from `places`where `places`.`name` = `places`.`selfreference-name`)

but the SELECT statement above is obviously wrong.但是上面的SELECT语句显然是错误的。 I am at a loss how to proceed.我不知道如何进行。

Any tips would be greatly appreciated.任何提示将不胜感激。

All best, Tench一切顺利,丁奇

Edit: the desired output would look like this:编辑:所需的输出如下所示:

id     | name   | selfreference | selfreference-name
------ | -------| --------------| ------------------ 
1      | Vienna |               |  
2      | Wien   |  1            | Vienna
3      | Виена  |  1            | Vienna

Could be you need a self join你可能需要一个自我加入

chekc with select使用选择检查

select a.*, b.*
from  `places` as a
inner join `places` as b

where b.`name` = a.`selfreference-name`;

and then if the query above give you the right result然后如果上面的查询给你正确的结果

update `places` as a
inner join `places` as b
set b.`selfreference` =  ab.`id`
where b.`name` = a.`selfreference-name`;

The following query does the job:以下查询完成了这项工作:

UPDATE places p1
INNER JOIN places p2 ON p1.`name` = p2.`selfreference-name`
SET p2.selfreference = p1.id;

p2 -> instance of table places which will be updated. p2 -> 将更新的表places实例。

p1 -> instance of table places from where the id of the matching selfreference-name is taken. p1 -> 表的实例places从中获取匹配的selfreference-nameid

WORKING DEMO BEFORE UPDATING更新前的工作演示

WORKING DEMO AFTER UPDATING更新后的工作演示

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

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