[英]Creating a foreign key in SQLAlchemy fails
我希望每个用户都具有一个称为allocatedstorage
和availablestorage
的值。 这两个值存储在另一个表中。 但是,当我创建以下数据库时,它显示以下错误。 我究竟做错了什么? 谢谢你的帮助。
class User(UserMixin, db.Model):
__tablename__ = 'user'
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(15), unique=True)
email = db.Column(db.String(50), unique=True)
password = db.Column(db.String(80))
role= db.Column(db.String(20));
usersessiontoken = db.Column(db.String(500), unique=True)
hasstorage = db.Column(db.Integer, db.ForeignKey('storageinformation.allocatedstorage'))
hasavailablestorage = db.Column(db.Integer, db.ForeignKey('storageinformation.availablestorage'))
storageinformation = db.relationship('StorageInformation', backref='user')
class StorageInformation(UserMixin, db.Model):
__tablename__ = 'storageinformation'
id = db.Column(db.Integer, primary_key=True)
allocatedstorage = db.Column(db.Integer)
availablestorage = db.Column(db.Integer)
错误:
sqlalchemy.exc.IntegrityError: (pymysql.err.IntegrityError) (1215, 'Cannot add foreign key constraint') [SQL: '\nCREATE TABLE user (\n\tid INTEGER NOT NULL AUTO_INCREMENT, \n\tusername VARCHAR(15), \n\temail VARCHAR(50), \n\tpassword VARCHAR(80), \n\t`role` VARCHAR(20), \n\tusersessiontoken VARCHAR(500), \n\thasstorage INTEGER, \n\thasavailablestorage INTEGER, \n\tPRIMARY KEY (id), \n\tUNIQUE (username), \n\tUNIQUE (email), \n\tUNIQUE (usersessiontoken), \n\tFOREIGN KEY(hasstorage) REFERENCES storageinformation (allocatedstorage), \n\tFOREIGN KEY(hasavailablestorage) REFERENCES storageinformation (availablestorage)\n)\n\n']
命令为 ALTER TABLE assignment ADD FOREIGN KEY(session_id) REFERENCES battery (session_id)
实际问题 Create table 'db_name/#sql-5f9_11e' with foreign key constraint failed. There is no index in the referenced table where the referenced columns appear as the first columns. Cannot add foreign key constraint
Create table 'db_name/#sql-5f9_11e' with foreign key constraint failed. There is no index in the referenced table where the referenced columns appear as the first columns. Cannot add foreign key constraint
MySQL需要在外键和引用键上建立索引,以便外键检查可以快速进行,而无需进行表扫描。 在引用表中,必须有一个索引,其中外键列以相同的顺序列为第一列。
InnoDB允许外键引用任何索引列或列组。 但是,在引用表中,必须有一个索引,其中引用列以相同的顺序列为第一列。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.