简体   繁体   中英

#1452 MySQL Error: alter table add foreign key

I have two tables (cliente, usuario), when I try add foreign key for cliente, referencing table usuario, it is cause error 1452

Table Cliente

id          int             primary key     auto_increment
nome        varchar(50)     not null
telefone    varchar(14)
email       varchar(30)
id_usuario  int             not null

-------------------------------------------------------------------------
Table Usuario

id      int             primary key     auto_increment
nome    varchar(50)     not null
email   varchar(30)     not null

My alter table sql

ALTER TABLE cliente
ADD FOREIGN KEY (id_usuario) REFERENCES usuario(id);

Where is problem for cause this error?

error:

Error Code: 1452. Cannot add or update a child row: a foreign key constraint fails (`pedidosystem`.`#sql-25ac_5f`, CONSTRAINT `#sql-25ac_5f_ibfk_1` FOREIGN KEY (`id_usuario`) REFERENCES `usuario` (`id`))

As a commenter said, you have one or more rows in cliente with id_usario values that don't appear anywhere in usario.id . You'll have to fix this before you create your foreign key constraint.

You can locate the offending records in cliente like this, before you create the fk.

SELECT cliente.*
  FROM cliente
  LEFT JOIN usario on cliente.usario_id = usario.id
 WHERE usario.id = NULL

Once you know which records are bad, you can update them or delete them.

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