gpt4 book ai didi

python - MySQL 主键作为外键 - 约束错误

转载 作者:行者123 更新时间:2023-11-29 21:55:30 24 4
gpt4 key购买 nike

假设我有 3 张 table 。

CREATE TABLE IF NOT EXISTS GROUP ( 
ID_GROUP INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
GROUP VARCHAR(50) NOT NULL,
INDEX(GROUP)
) ENGINE=INNODB DEFAULT CHARACTER SET = utf8 COLLATE = utf8_general_ci;)

CREATE TABLE IF NOT EXISTS USERZ (
ID CHAR(8) NOT NULL,
GROUP VARCHAR(50) NOT NULL,
FIRST_NAME VARCHAR(100) NULL DEFAULT NULL ,
LAST_NAME VARCHAR(100) NULL DEFAULT NULL,
DATE_CREATED TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
PASSWORD VARCHAR(8) NULL DEFAULT 'HELLOWORLD',
PRIMARY KEY (ID),
INDEX (ID),
INDEX (GROUP),
FOREIGN KEY (GROUP) REFERENCES GROUP (GROUP)
) ENGINE=INNODB DEFAULT CHARACTER SET = utf8 COLLATE = utf8_general_ci;)


CREATE TABLE IF NOT EXISTS WORKERS (
ID CHAR(8) NOT NULL PRIMARY KEY,
DATE_START TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
DATE_END TIMESTAMP NULL,
FOREIGN KEY (ID) REFERENCES USERZ (ID)
) ENGINE=INNODB DEFAULT CHARACTER SET = utf8 COLLATE = utf8_general_ci;)

我在表 USERZ 中插入数据没有问题。但是当需要向表 WORKERS 添加记录时,我收到错误消息:

mysql.connector.errors.IntegrityError: 1452 (23000): 无法添加或更新子行:外键约束失败 (DATABASENAME.WORKERS, CONSTRAINT WORKERS_ibfk_1外键(ID)引用USERZ(ID))

我确信这是 WORKERS 主键 (ID) 引用 USERZ (ID) 的内容。即使我知道 USERZ 中存在 USERZ id,它也不会让我向 WORKERS 添加数据。通过下面的示例,我知道 USERZ 表中存在“XXXXXXX1”,因此我想能够在 WORKERS 表中添加此用户。

示例:

"INSERT INTO WORKERS (ID) VALUES ('XXXXXXX1') "

谢谢你!

最佳答案

您不应该让主键 id 也成为外键。将其重构为这样

CREATE TABLE IF NOT EXISTS WORKERS (   
ID CHAR(8) NOT NULL PRIMARY KEY,
USER_ID CHAR(8) NOT NULL,
DATE_START TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
DATE_END TIMESTAMP NULL,
FOREIGN KEY (USER_ID) REFERENCES USERZ (ID)
) ENGINE=INNODB DEFAULT CHARACTER SET = utf8 COLLATE = utf8_general_ci;)

然后你的插入应该是

INSERT INTO WORKERS (USER_ID) VALUES ('XXXXXXX1')

关于python - MySQL 主键作为外键 - 约束错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33191873/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com