ERROR 1452: Cannot add or update a child row: a foreign key constraint fails

后端 未结 21 1741
野性不改
野性不改 2020-11-22 07:01

I have created tables in MySQL Workbench as shown below :

ORDRE table:

CREATE TABLE Ordre (
  OrdreID   INT NOT NULL,
  OrdreDato DA         


        
21条回答
  •  粉色の甜心
    2020-11-22 07:36

    I had the same problem. I was creating relationships on existing tables but had different column values, which were supposed/assumed to be related. For example, I had a table USERS that had a column USERID with rows 1,2,3,4,5. Then I had another child table ORDERS with a column USERID with rows 1,2,3,4,5,6,7. Then I run MySQl command ALTER TABLE ORDERS ADD CONSTRAINT ORDER_TO_USER_CONS FOREIGN KEY (ORDERUSERID) REFERENCES USERS(USERID) ON DELETE SET NULL ON UPDATE CASCADE;

    It was rejected with the message:

    Error Code: 1452. Cannot add or update a child row: a foreign key constraint fails (DBNAME1.#sql-4c73_c0, CONSTRAINT ORDER_TO_USER_CONS FOREIGN KEY (ORDERUSERID) REFERENCES USERS (USERID) ON DELETE SET NULL ON UPDATE CASCADE)

    I exported data from the ORDERS table, then deleted all data from it, re-run the command again, it worked this time, then re-inserted the data with the corresponding USERIDs from the USERS table.

提交回复
热议问题