[英]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.