首先,tags_unified
通过INSERT INTO ...SELECT
使用UNION
. 结果将是两个表中所有标签的不同集合。
CREATE TABLE tags_unified (
tags_id INT PRIMARY KEY AUTO_INCREMENT,
tag_name VARCHAR(64)
);
/* Load up all the tags with new ids */
INSERT INTO tags_unified (tag_name)
SELECT tag_name FROM article_tags
UNION
SELECT tag_name FROM image_tags
然后UPDATE
所有的individual_image_tags
和inidividual_article_tags
用一个JOIN
查询来获取新的ID。
UPDATE
individual_image_tags
JOIN image_tags ON individual_image_tags.tag_id = image_tags.tag_id
/* LEFT JOIN the old tags to the new tags by tag_name */
LEFT JOIN tags_unified ON image_tags.tag_name = tags_unified.tag_name
SET individual_image_tags.tag_id = tags_unified.tag_id
/* And update those which have a match in the new tags table */
WHERE tags_unified.tag_id IS NOT NULL
UPDATE
individual_article_tags
JOIN article_tags ON individual_article_tags.tag_id = article_tags.tag_id
LEFT JOIN tags_unified ON article_tags.tag_name = tags_unified.tag_name
SET individual_article_tags.tag_id = tags_unified.tag_id
WHERE tags_unified.tag_id IS NOT NULL
在运行UPDATE
语句之前,将它们重新形成为SELECT
语句以验证结果。
SELECT
individual_image_tags.*,
tags_unified.*
FROM
individual_image_tags
JOIN image_tags ON individual_image_tags.tag_id = image_tags.tag_id
LEFT JOIN tags_unified ON image_tags.tag_name = tags_unified.tag_name
WHERE tags_unified.tag_id IS NOT NULL
SELECT
individual_article_tags.*,
tags_unified.*
FROM
individual_article_tags
JOIN article_tags ON individual_article_tags.tag_id = article_tags.tag_id
LEFT JOIN tags_unified ON article_tags.tag_name = tags_unified.tag_name
WHERE tags_unified.tag_id IS NOT NULL
编辑:
LEFT JOIN
andWHERE
子句实际上不应该是必需的,因为应该是表中每个现有标记的匹配项tags_unified
。
评论后更新:
创建临时表并从中重新填充原始链接表可能比删除和重新添加唯一约束或复合键更容易。使用CREATE TEMPORARY TABLE AS SELECT...
. 然后从原始表中删除所有行并用于INSERT INTO ... SELECT
从临时表中重新填充它。
CREATE TEMPORARY TABLE temp_individual_article_tags AS
SELECT
individual_article_tags.article_id
tags_unified.tag_id
FROM
individual_article_tags
JOIN article_tags ON individual_article_tags.tag_id = article_tags.tag_id
LEFT JOIN tags_unified ON article_tags.tag_name = tags_unified.tag_name
WHERE tags_unified.tag_id IS NOT NULL