加外键报错?

对已有的表加外键, 如果已经存在数据了, 可能会报错:

sqlalchemy.exc.IntegrityError: (MySQLdb.IntegrityError) (1452, 'Cannot add or update a child row: a foreign key constraint fails (`verman`.`#sql-332_4c`, CONSTRAINT `#sql-332_4c_ibfk_9` FOREIGN KEY (`store_id`) REFERENCES `store` (`id`))')
[SQL: ALTER TABLE version ADD FOREIGN KEY(store_id) REFERENCES store (id)]
(Background on this error at: https://sqlalche.me/e/14/gkpj)

这个时候可以在执行增加外键语句前执行:

SET FOREIGN_KEY_CHECKS=0;

执行完之后再执行:

SET FOREIGN_KEY_CHECKS=1;