Reputation: 9007
i had a table that a used to have one to one relation using parent_id column, our logic changed and we needed to enable many to many so we -unforunatly- didn't have luxury to change database model, so we used to insert multiple rows one for each relation and group them after wards in code.
now i need to restructure mysql table to reflect many to many relation.
example
Table Blog
ID, Body, target_id, grouping
1 etc 1 1
2 etc 2 1
3 etc2 1 3
4 etc2 2 3
Currently, when ever we are creating a new blog post. we insert the first row. grap its id, and replicate insert for each target.
so now as db grew much larger. we need to stop this and create an intermediate table that hold relations. so above table will become
Table Blog
ID, Body
1 etc
3 etc2
Table Blog_target
blog_id,target_id
1 , 1
1 , 2
3 , 1
3 , 2
so how can i split data from old table into new without losing any data in mysql?
Upvotes: 0
Views: 1080
Reputation: 371
I don't know if this will help your case, but I had to change a oneToMany table relation into a manyToMany table, and below is how I achieved that.
One easy way to do that is simply just drop the unique constraint of that column with the following command:
ALTER TABLE relation_table DROP INDEX UK_constraint_id;
If you have MySql Workbench installed it is even easier, because you don't need to discover the constraint id. Just select your table -> alter table and unmark the UQ checkbox of the column and then click on "Apply".
If you do not have MySql Workbench installed you can do the following query to find out the constraint id:
USE INFORMATION_SCHEMA;
SELECT TABLE_NAME,
COLUMN_NAME,
CONSTRAINT_NAME,
REFERENCED_TABLE_NAME,
REFERENCED_COLUMN_NAME
FROM KEY_COLUMN_USAGE
WHERE TABLE_SCHEMA = "<schema_name>"
AND TABLE_NAME = "<table_name>";
and just use the ALTER TABLE mentioned above.
Upvotes: 0
Reputation: 6202
something like this maybe? new_blog table because your blog table already exists, after you're all done and happy with the data in new_blog table and blog_target table, you can just drop your blog table and RENAME TABLE new_blog TO blog;
INSERT INTO new_blog(ID, Body)
SELECT DISTINCT grouping, body FROM blog;
INSERT INTO blog_target(blog_id,target_id)
SELECT grouping,target_id
FROM blog;
Upvotes: 1