如何更新一列以匹配同一表中另一列的数据

时间:2019-12-25 21:53:49

标签: mysql sql mariadb

我正在尝试执行一条查询,该查询将更新parent_id行,以反映具有与parent_id相同member_id的相应用户名。

下面是 db_name.members 表的表示,我想将parent_id转换为其相应的用户名。

+--------+----------+-----------+-----------+
|  name  | username | member_id | parent_id |
+--------+----------+-----------+-----------+
| Jeff   | Jeff     |       167 | NULL      |
| Asia   | Asia     |       143 | NULL      |
| Bogart | Bogart   |       389 | 167       |
| Greg   | Greg     |       894 | NULL      |
| Hatsy  | Hatsy    |       328 | 167       |
| Super  | Super    |       721 | NULL      |
| Goku   | Goku     |       534 | 894       |
| Banana | Banana   |       520 | NULL      |
| Kyle   | Kyle     |       456 | 520       |
+--------+----------+-----------+-----------+

它的外观如下:

+--------+----------+-----------+-----------+
|  name  | username | member_id | parent_id |
+--------+----------+-----------+-----------+
| Jeff   | Jeff     |       167 | NULL      |
| Asia   | Asia     |       143 | NULL      |
| Bogart | Bogart   |       389 | Jeff      |
| Greg   | Greg     |       894 | NULL      |
| Hatsy  | Hatsy    |       328 | Jeff      |
| Super  | Super    |       721 | NULL      |
| Goku   | Goku     |       534 | Greg      |
| Banana | Banana   |       520 | NULL      |
| Kyle   | Kyle     |       456 | Banana    |
+--------+----------+-----------+-----------+

这是我当前(无效)的查询:

UPDATE members SET parent_id=(SELECT name FROM members WHERE member_id=parent_id);

1 个答案:

答案 0 :(得分:2)

您可以将The mandatory attribute 'amp-custom' is missing in tag 'style amp-custom (transformed)'.UPDATE一起使用:

INNER JOIN

请记住,如果UPDATE members m1 INNER JOIN members m2 ON m1.parent_id = m2.member_id SET m1.parent_id = m2.username 列是整数/数字列,则不能将用户名设置为此列。您可以使用parent_id代替SELECT

UPDATE

demo on dbfiddle.uk