How to change one-to-one relationship to one-to-many relationship in MySQL?

3.2k Views Asked by At

I currently have a user's table which contains a one-to-one relationship for Youtube OAuth tokens. However, I now want to support multiple video sites and want to break this into a one-to-many relationship.

I have setup the new tables:

tokens - cols: id, site, username (the user's username on Youtube), oauth_token, oauth_secret

user_tokens - cols: id, user_id, token_id

Is there a way I can SELECT from my current user's table INTO these tables to import the username, oauth_token and oauth_secret columns while also setting up the user_tokens table with the appropriate id's?

In the past I have written short PHP scripts to do this, but have always been curious about whether I can do it directly in MySQL.

2

There are 2 best solutions below

1
On BEST ANSWER

You don't need a relation table for a one-to-many relationship, you just need a user_id field in the tokens table. That also makes it easier to poultate the table:

insert into tokens (site, user_id, username, oauth_token, oauth_secret)
select site, user_id, username, oauth_token, oauth_secret
from users

(As I don't know exactly what's in your user table and what the field names are, it might need some adjusting.)

0
On

Checkout MySQL documentation. I think that should help you.