I have 2 tables (customers and cars with FK) and in the beginning everything was OK, I was able to insert data until ID 7 and then all of a sudden it just stopped working and gave me an error 1452. Tried to search for solution but nothing helped.
Error Code: 1452. Cannot add or update a child row: a foreign key constraint fails (`test`.`cars`, CONSTRAINT `personid` FOREIGN KEY (`id`) REFERENCES `customer` (`id`))
So here are the tables:
CREATE TABLE `customer` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`lastname` varchar(45) NOT NULL,
`firstname` varchar(45) NOT NULL,
`city` varchar(45) NOT NULL,
`age` varchar(45) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `id_UNIQUE` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=14 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
and
CREATE TABLE `cars` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`brand` varchar(45) NOT NULL,
`model` varchar(45) NOT NULL,
`reg` varchar(45) NOT NULL,
`personid` int(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `id_UNIQUE` (`id`),
CONSTRAINT `personid` FOREIGN KEY (`id`) REFERENCES `customer` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=30 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
I think I found the problem and solution (kind of).
Updating an existing AUTO_INCREMENT column value also resets the AUTO_INCREMENT sequence.
So it stopped automatically assigning id to cars table and it worked only if I add id manually. Then I did this: ALTER TABLE tbl AUTO_INCREMENT = 12;
and seems to be working now. But still don't know how it stopped working and can't remember to have updated existing AUTO_INCREMENT. Anyway leaving this as an answer.