MYSQL将标记表合并为一个

时间:2013-01-26 22:55:57

标签: php mysql database-design

我有桌子来组织标签..

3篇文章和文章标签:

article_tags
---
tag_id *
tag_name

articles
---
article_id *
article_name 

individual_article_tags
----
article_id *
tag_id *

和3个单独的图像和图像标签表

image_tags
---
tag_id *
tag_name

images
---
image_id *
image_name 

individual_image_tags
----
image_id *
tag_id *

我希望文章和图像表仅引用1个标记表而不是2个标记表,如下所示:

tags
---
tag_id *
tag_name

articles
---
article_id *
article_name 

individual_article_tags
----
article_id *
tag_id *

images
---
image_id *
image_name 

individual_image_tags
----
image_id *
tag_id *

问题是标签有不同的ID,我不知道如何合并它们。

1 个答案:

答案 0 :(得分:2)

首先,通过tags_unifiedINSERT INTO ...SELECT创建一个新的UNION表,其中包含自己的auto_increment id(与其他任何现有表不同)。结果将是两个表中所有标记的不同集合。

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_tagsinidividual_article_tags JOIN查询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 以获取新ID。

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

编辑:

实际上不需要WHEREtags_unified子句,因为匹配CREATE TEMPORARY TABLE AS SELECT...表中的每个现有标记。< / p>

评论后更新:

创建临时表并重新填充原始链接表可能比删除和重新添加唯一约束或复合键更容易。使用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 从临时表中重新填充它。

{{1}}