我要说这3张桌子。
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
FOREIGN KEY (ID
)参考USERZ
(ID
))
我确信这是WORKERS主键(ID)指的是USERZ(ID)。即使我知道USERZ中存在USERZ ID,它也不会让我向WORKERS添加数据。以下为例,我知道' XXXXXXX1'存在于USERZ表中,因此我假设能够在WORKERS表中添加此用户。
例如:
"INSERT INTO WORKERS (ID) VALUES ('XXXXXXX1') "
谢谢!
答案 0 :(得分:0)
你不应该将主键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')