开发者

Reversing a 1:many relationship between two tables

I have two MySQL tables A and B. Table A has a member ref which is a ForeignKey reference to B.id. This makes for a 1:many association between B and A.

This has been in production for a few weeks, but I'm now adding more features to my code and have realized I got my original mapping wrong. I needed a many:1 relationship between B and A. That is, B.ref should point to A.id, not the other way around. It wasn't a problem until now because it was all 1:1 mapping so far. How do I migrate my data to the new schema?

I'd guess:

  1. ALTER TABLE B ADD COLUMN ref INTEGER CONSTRAINT FOREIGN KEY (A.id) -- add the column first
  2. Run the SQL equivalent of "for row in A: row.ref.ref = row开发者_如何学C"
  3. ALTER TABLE A DROP COLUMN ref

Attempting to do this in SQLAlchemy fails with a circular reference error. I need to do it in SQL, but am not familiar with the necessary SELECT+UPDATE syntax. Help?


For step 2:

update b, a
    set b.ref = a.id
    where a.ref = b.id


Just add the foreign key constraint as fourth step, you won't need it when creating the column.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜