I have tables to organize tags..
3 tables for articles and article tags:
article_tags
---
tag_id *
tag_name
articles
---
article_id *
article_name
individual_article_tags
----
article_id *
tag_id *
AND 3 separate tables for images and images tags
image_tags
---
tag_id *
tag_name
images
---
image_id *
image_name
individual_image_tags
----
image_id *
tag_id *
I want the articles and images tables to reference Only 1 tag table instead of 2 tag tables like so:
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 *
The problem is that the tags have different IDs and I don’t know how to merge them..
First, create an new
tags_unifiedtable with its own auto_increment id (which will differ from either of the other existing tables) by doingINSERT INTO ...SELECTwith aUNION. The result will be a distinct set of all tags from both tables.Then
UPDATEall theindividual_image_tagsandinidividual_article_tagswith aJOINquery to get the new ids.Before running the
UPDATEstatements, re-form them asSELECTstatements to verify the results.Edit:
The
LEFT JOINand theWHEREclause should not actually be necessary, because the should be a match for every existing tag in thetags_unifiedtable.Update after comments:
It may be easier to create temporary tables and repopulate the original link tables from those than to drop and re-add unique constraints or composite keys. Use
CREATE TEMPORARY TABLE AS SELECT.... Then delete all rows from the original table and useINSERT INTO ... SELECTto re-fill it from the temp table.