[英]Convert many to many to one to one (mysql)
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. 我们更改了数据库架构,并使用联接表accounts_users将用户/帐户之间的关系从1-1移动到多对多。
So we have accounts, users, accounts_users (user_id and account_id) 因此,我们有帐户,用户,accounts_users(user_id和account_id)
Our data is still 1-1, and we have decided to move back. 我们的数据仍然是1-1,因此我们决定退回去。 So I need sql to move back:
因此,我需要使用sql来回退:
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. 所有这些都会产生某种SQL错误。 Im guessing its because my sql is ambiguous, and I need some sort of select first or min or something like that.
我猜测是因为我的sql模棱两可,所以我需要先进行某种选择,然后再进行min或类似的选择。
** 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. **要明确,我确定数据中仍然具有1-1关系,但是我无法弄清楚sql将现有表中的数据重新带回原始表中。 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.
我正在寻找的是一些可以运行的sql,它将从accounts_users中获取数据并将user_id放入account表中。 Thanks, Joel
谢谢,乔尔
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). 这会变得非常乏味,如果你有很多的列
accounts_users
是要回去的accounts
,不过,如果有与IDS(因此我以前的答案)任何问题,将无法正常工作。 How many columns are there? 有几列?
如果您的映射是1-1,则只需选择第一个结果(您知道只有一个结果)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.