简体   繁体   中英

convert table from one to many into many to many MYSQL

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?

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;

sqlfiddle

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM