问题描述
|
给定具有表的MysqL数据库,如下所示:
author:
+----+----------+
| id | name |
+----+----------+
| 1 | John |
| 2 | Peter |
| 3 | Peter |
+----+----------+
article:
+----+-----------+------+
| id | author_id | text |
+----+-----------+------+
| 1 | 2 | ... |
| 2 | 3 | ... |
| 3 | 3 | ... |
+----+-----------+------+
并非偶然将author-table的名称列设置为unique。现在,我必须将相关文章“合并”到相关作者之一中,即将第2条和第3条的author_id设置为2。我想在此之后使名称列唯一。
我不能手动重新分配文章,因为受影响的记录太多了。但我认为可能已经有解决此问题的方法/摘要。
解决方法
要更新您的
article
表格,这将达到目的:
update article art
set art.author_id = (select min(aut.id)
from author aut
where aut.name = (select a.name
from author a
where a.id = art.author_id));
select * from article;
+ ------- + -------------- + --------- +
| id | author_id | text |
+ ------- + -------------- + --------- +
| 1 | 2 | |
| 2 | 2 | |
| 3 | 2 | |
+ ------- + -------------- + --------- +
3 rows
如果您希望进行更紧凑的更新(并且进行更优化),则可以使用此更新,其工作方式相同:
update article art
set art.author_id = (select min(aut.id)
from author aut
inner join author a on a.name = aut.name
where a.id = art.author_id);
最后,要删除多余的作者,您需要
delete a
from author a
inner join (
select name,min(id) as min -- this subquery returns all repeated names and their smallest id
from author
group by name
having count(*) > 1) repeated on repeated.name = a.name
where a.id > repeated.min; -- delete all repeateds except the first one
select * from author;
+ ------- + --------- +
| id | name |
+ ------- + --------- +
| 1 | John |
| 2 | Peter |
+ ------- + --------- +
2 rows
这适用于许多重复的作者集。
希望这可以帮助
, 您可以先撰写更新文章,以使用具有相同名称的最低作者ID
UPDATE art SET art.author_id =
(SELECT MIN(a1.id) FROM author a1 WHERE a1.Name = a2.name
FROM article art INNER JOIN author a2 ON art.author_id = a2.id)
然后删除同名的上级作者
PS。我尚未测试SQL,但应该可以工作。