如何更新一个外键字段,它实际上是其父项中具有唯一 ID 的重复项?
How to update a foreign key field which is actually a duplicate in its parent with unique id?
我有一个 Widget
table,字段为 [id(primary key), label}
。这个 table 以某种方式作为重复的 label
字段如下所示。
+-----+----------+
| id | label |
+-----+----------+
| 01 | Customer |
| 02 | Client |
| 03 | Customer |
| 04 | Customer |
| 05 | Customer |
| 06 | Client |
| 07 | Client |
+-----+----------+
还有一个名为 company
的 table,外键为 label_id
。外键可以为空。
+-----+------+----------+
| id | name | label_id |
+-----+------+----------+
| 400 | ABC | 01 |
| 401 | DEF | 02 |
| 402 | ADF | 06 |
| 403 | QWE | 05 |
| 404 | RST | 06 |
| 405 | WAS | null |
+-----+------+----------+
因为 label_id
06
和 05
是重复的,因为它们指向相同的 Customer
和 Client
标签。我需要将它们重新分配给 id 01 和 02 以及具有此类重复 label_ids 的所有其他记录。之后删除 Widget
table.
中的所有重复记录
Note :`CASCADE on DELETE` referential action is not applied in my table.
需要有关如何执行此操作的建议??
不确定您的要求,但可能是这样的
UPDATE Company C
SET
`label_id` = (SELECT MIN(`id`)
FROM Widget
WHERE `label` = (SELECT `label`
FROM Widget W
WHERE W.`id` = C.`label_id`)
);
输出
| id | name | label_id |
|-----|------|----------|
| 400 | ABC | 1 |
| 401 | DEF | 2 |
| 402 | ADF | 2 |
| 403 | QWE | 1 |
| 404 | RST | 2 |
| 405 | WAS | (null) |
我有一个 Widget
table,字段为 [id(primary key), label}
。这个 table 以某种方式作为重复的 label
字段如下所示。
+-----+----------+
| id | label |
+-----+----------+
| 01 | Customer |
| 02 | Client |
| 03 | Customer |
| 04 | Customer |
| 05 | Customer |
| 06 | Client |
| 07 | Client |
+-----+----------+
还有一个名为 company
的 table,外键为 label_id
。外键可以为空。
+-----+------+----------+
| id | name | label_id |
+-----+------+----------+
| 400 | ABC | 01 |
| 401 | DEF | 02 |
| 402 | ADF | 06 |
| 403 | QWE | 05 |
| 404 | RST | 06 |
| 405 | WAS | null |
+-----+------+----------+
因为 label_id
06
和 05
是重复的,因为它们指向相同的 Customer
和 Client
标签。我需要将它们重新分配给 id 01 和 02 以及具有此类重复 label_ids 的所有其他记录。之后删除 Widget
table.
Note :`CASCADE on DELETE` referential action is not applied in my table.
需要有关如何执行此操作的建议??
不确定您的要求,但可能是这样的
UPDATE Company C
SET
`label_id` = (SELECT MIN(`id`)
FROM Widget
WHERE `label` = (SELECT `label`
FROM Widget W
WHERE W.`id` = C.`label_id`)
);
输出
| id | name | label_id |
|-----|------|----------|
| 400 | ABC | 1 |
| 401 | DEF | 2 |
| 402 | ADF | 2 |
| 403 | QWE | 1 |
| 404 | RST | 2 |
| 405 | WAS | (null) |