简体   繁体   中英

MySQL Primary Key as Foreign Key - Constraint error

Let say i've theses 3 tables.

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;)

i've no problem insert data in table USERZ. But when it comes to add a record to the table WORKERS, i get the error messages :

mysql.connector.errors.IntegrityError: 1452 (23000): Cannot add or update a child row: a foreign key constraint fails ( DATABASENAME . WORKERS , CONSTRAINT WORKERS_ibfk_1 FOREIGN KEY ( ID ) REFERENCES USERZ ( ID ))

I know for sure this is something with WORKERS Primary Key (ID) Refers to USERZ (ID). It won't let me add data to WORKERS even if i know that the USERZ id exists in USERZ. With the exemple below, i know that 'XXXXXXX1' exist in USERZ table, so im suppose to be able to add this users in the WORKERS table.

in example :

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

Thanks you !

you should not have the primary key id be a foreign key as well. refactor it to be like this

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;)

and then your insert should be

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM