我试图将Leaderinfo表中的外键定义为UserID,这是usercredentials表中的主键。
USERtable="CREATE TABLE IF NOT EXISTS usercredentials (userID VARCHAR(255),username VARCHAR(255),password VARCHAR(255),stakeholder VARCHAR(255))"
mycursor.execute(USERtable)
LEADERtable="""CREATE TABLE IF NOT EXISTS leaderinfo (leaderID VARCHAR(255),firstname VARCHAR(255),secondname VARCHAR(255),age VARCHAR(255), \
gender VARCHAR(255),ethnicity VARCHAR(255),address VARCHAR(255),postcode VARCHAR(255),telephone VARCHAR(255), \
email VARCHAR(255),userID VARCHAR(255),PRIMARY KEY(leaderID),FOREIGN KEY(userID) REFERENCES usercredentials(userID) on update cascade on delete cascade)"""
错误代码:
mysql.connector.errors.DatabaseError: 1822 (HY000): Failed to add the foreign key constraint. Missing index for constraint 'leaderinfo_ibfk_1' in the referenced table 'usercredentials'
答案 0 :(得分:1)
在领导者表中引用的列未编制索引。您可以通过将userID
列用作主键来解决此问题(为便于阅读,我将在此处包装SQL):
USERtable="CREATE TABLE IF NOT EXISTS usercredentials (
userID VARCHAR(255),
username VARCHAR(255),
password VARCHAR(255),
stakeholder VARCHAR(255),
PRIMARY KEY(userID))"