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:
ALTER TABLE B ADD COLUMN ref INTEGER CONSTRAINT FOREIGN KEY (A.id)— add the column first- Run the SQL equivalent of “
for row in A: row.ref.ref = row“ 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: