Pergunta

We changed database schema and moved a relationship between users/accounts from a 1-1 to a many to many using a join table accounts_users.

So we have accounts, users, accounts_users (user_id and account_id)

Our data is still 1-1, and we have decided to move back. So I need sql to move back:

To Migrate I used:

INSERT INTO accounts_users (account_id,user_id) SELECT id AS account_id, user_id AS user_id FROM accounts

To move back I have tried:

UPDATE 
    accounts
SET
    user_id = ru.user_id
FROM 
    accounts r, accounts_users ru
ON 
    r.id = ru.account_id


Update accounts
Set r.user_id = ru.user_id
FROM accounts r, accounts_users ru
WHERE r.id = ru.account_id


SELECT accounts_users.user_id
   INTO accounts
   FROM accounts_users
   INNER JOIN accounts
   ON accounts.id = accounts_users.account_id

All of these give a sql error of some sort. Im guessing its because my sql is ambiguous, and I need some sort of select first or min or something like that.

** To be clear, Im sure still have the 1-1 relationship in the data, but I cant figure out the sql to bring the data from the existing tables back into the original tables. What im looking for is some working sql that will take the data from accounts_users and put the user_id into the account table. Thanks, Joel

Foi útil?

Solução

You could try...

UPDATE accounts
    SET user_id = (SELECT user_id
                       FROM accounts_users
                       WHERE accounts_users.accounts_id = accounts.accounts_id);

That'll get pretty tedious if you have a lot of columns in accounts_users that have to go back in accounts, though, and won't work if there is any problems with the ids (hence my previous answer). How many columns are there?

Outras dicas

If your mapping is 1-1 then just select the first result (you know there is only one)

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top