python - 缺少索引约束添加外键

标签 python mysql

我试图将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'

最佳答案

您在前导表中引用的列未建立索引。您可以通过将 userID 列设为主键来解决此问题(为了便于阅读,我将在此处包装 SQL):

USERtable="CREATE TABLE IF NOT EXISTS usercredentials (
           userID VARCHAR(255),
           username VARCHAR(255),
           password VARCHAR(255),
           stakeholder VARCHAR(255),
           PRIMARY KEY(userID))"

关于python - 缺少索引约束添加外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53227597/

相关文章:

python - 在 Heroku 上使用环境变量作为凭证

python - 识别 python DataFrame 中相等的行...

python - 将 QPixmap 转换为 Numpy

带有 sequelize 和 Node js 的 Mysql native 空间函数

php - php表格中的复选框

mysql - 在 Wamp 上安装 MySQL 插件

python - 在 python 中迭代一个漂亮的 soup 数组

python - 转换为(不是从)ipython Notebook 格式

mysql - RAND()在MySQL中的分布

PHP & MySQL : Count and order most popular values in an array and then print