开发者

Refactoring a One-to-many relation to a Many-to-Many in MySQL: How to formulate the query?

开发者 https://www.devze.com 2023-04-13 01:39 出处:网络
In the initial \'version\' of the application that I\'m working on, a design consideration wasn\'t taken into account - no one thought of it.

In the initial 'version' of the application that I'm working on, a design consideration wasn't taken into account - no one thought of it.

However, it seems that the original one-to-many relation needs to be refactored into a many-to-many. My question is how best to do this? I'm using MySQL for persistence.

Populating the relationship table will only be a one time effort, I'd rather go with a simple query or a stored procedure approach (I'm not well versed with the latter); rather than write java/jdbc based logic to do it (I know I can and it's not too difficult, but that's not what I want)

So here's an example of the relation:

|VirtualWhiteBoard| -1------*- |Post|

A virtual white board can have many posts. The new functionality is: 1 post should belong to multiple white boards if the user chooses to 'duplicate' current white board (not thought of before)

The schema looks like this:

VirtualWhiteBoard (wallName, projectName,dateOfCreation,..., Primary_Key(wallName, projectName));
Post(post_id, wallName,postData,..., Primary_Key(post_id), Foreign_Key(wallName, projectName));

The virtual white board has a composite开发者_运维知识库 primary key (wallName, projectName) and each post has a post_id as primary key

Question: Take the primary keys from VirtualWhiteBoard and Post and add it to the new relation 'has_posts':

|VirtualWhiteBoard| -1------*- |has_Post| -*------1- |Post|

To keep the previous relationships intact and then drop the foreign key column of wallName in Post.

How best to achieve this? Would a query suffice or stored procedures would be required?

(Although I can do this in the 'application' I'd prefer to do it this way, since such refactorings are bound to arise and I don't want unnecessary java-code lying around that'll need to be maintained and would personally prefer to have such a skill too :)


Create your has_Post table with two columns post_id and wallName and populate it with this query:

INSERT INTO has_Post(post_id, wallName) SELECT post_id, wallName FROM Post

Then delete the wallName column from Post table.

0

精彩评论

暂无评论...
验证码 换一张
取 消