MySQL Error Code: 1452. Cannot add or update a child row: a foreign key constraint fails

amrpk 16 Reputation points
2021-06-23T17:03:57.377+00:00

Im trying to insert values on this table using "insert into", but there is this error: "Error Code: 1452. Cannot add or update a child row: a foreign key constraint fails (TESTE.FUNCIONARIO, CONSTRAINT FUNCIONARIO_ibfk_1 FOREIGN KEY (CPF_SUPERVISOR) REFERENCES FUNCIONARIO (CPF))".

I cant find what is causing it.

This is the SHOW CREATE TABLE:

CREATE TABLE FUNCIONARIO (

PNOME varchar(10) DEFAULT NULL,

MINICIAL char(1) DEFAULT NULL,

UNOME varchar(10) DEFAULT NULL,

CPF varchar(11) NOT NULL,

DATANASC date DEFAULT NULL,

ENDERECO varchar(100) DEFAULT NULL, SEXO char(1) DEFAULT NULL,

SALARIO decimal(10,0) DEFAULT NULL,

CPF_SUPERVISOR varchar(11) NOT NULL,

DNR int DEFAULT NULL,

PRIMARY KEY (CPF),

KEY CPF_SUPERVISOR (CPF_SUPERVISOR),

KEY DNR (DNR),

CONSTRAINT FUNCIONARIO_ibfk_1 FOREIGN KEY (CPF_SUPERVISOR) REFERENCES FUNCIONARIO (CPF),

CONSTRAINT FUNCIONARIO_ibfk_2 FOREIGN KEY (DNR) REFERENCES DEPARTAMENTO (DNUMERO)

) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci

Anyone know what could be happening?

SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
12,706 questions
{count} vote

2 answers

Sort by: Most helpful
  1. Viorel 112.1K Reputation points
    2021-06-23T17:10:03.023+00:00

    Probably CPF_SUPERVISOR cannot be “NOT NULL”. Try making it “NULL”.

    When you insert a supervisor, specify NULL value for CPF_SUPERVISOR column.

    When you insert other people, specify the corresponding value of CPF column, which was already inserted before.

    0 comments No comments

  2. CarrinWu-MSFT 6,851 Reputation points
    2021-06-24T02:10:26.22+00:00

    Hi @amrpk ,

    Welcome to Microsoft Q&A!

    MySQL is not Microsoft product, and there have some difference between SQL Server and MySQL, suggest that post your question in some other forum, such as MySQL Forums. By the way, if you would like to ask some question about SQL Server T-SQL, please added tag sql-server-transaction-sql.

    And I did some research, this similar thread may be help you to resolved this error.

    Best regards,
    Carrin


    If the answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments