Trying to insert a row into MySQL using phpMyAdmin, and it is failing my with error:
#1452 - Cannot add or update a child row: a foreign key constraint fails (`staging`.`user_profiles`, CONSTRAINT `fk_user_profiles_users` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE)
Can't figure out why. I created the database design in MySQL Workbench and it was working on MySQL 5.7 in development and now won't work with Percona server 5.5. Where am I NOT looking??
SQL Statement and Error
Foriegn key in phpMyAdmin
This is the table structure I created in MySQL Workbench (dashes for obscuring client info =P):
DROP TABLE IF EXISTS `staging_-----------`.`users` ;
CREATE TABLE IF NOT EXISTS `staging_-----------`.`users` (
`id` INT NOT NULL AUTO_INCREMENT,
`email` VARCHAR(255) NOT NULL,
`password` VARCHAR(128) NOT NULL,
`role` ENUM('admin', 'vet', 'client') NOT NULL,
PRIMARY KEY (`id`));
DROP TABLE IF EXISTS `staging_-----------`.`user_profiles` ;
CREATE TABLE IF NOT EXISTS `staging_-----------`.`user_profiles` (
`user_id` INT NOT NULL,
`address_one` VARCHAR(255) NULL,
`address_two` VARCHAR(255) NULL,
`age` INT NULL,
`sex` ENUM('m', 'f') NULL,
`first_name` VARCHAR(45) NULL,
`last_name` VARCHAR(45) NULL,
`city` VARCHAR(45) NULL,
`state` VARCHAR(45) NULL,
`zip` VARCHAR(6) NULL,
`phone` VARCHAR(45) NULL,
`photo` VARCHAR(255) NULL,
PRIMARY KEY (`user_id`),
INDEX `fk_user_profiles_users2_idx` (`user_id` ASC),
CONSTRAINT `fk_user_profiles_users`
FOREIGN KEY (`user_id`)
REFERENCES `staging_-----------`.`users` (`id`)
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB;
I've been trying to get my working code working again for 2 days now, and no love. What could have gone wrong? Thank you so much for your time.
Check if the value you are inserting exists in user_id exists in staging_-----------.users
Maybe this is the problem ....
Related
I am setting up Microsoft ASP.NET Core Identity on my website as an exercise to move on to other web applications.
I have gotten to the part where I am trying to implement two factor authentication. I get an error as in the title because I do not have AspNetUserTokens as a table in my database. I cannot seem to find the schema for this detailed anywhere. Does anyone know the schema for this table?
This is the script I currently have for my database:
DROP DATABASE Membership;
CREATE DATABASE Membership;
USE Membership;
CREATE TABLE `AspNetRoles` (
`Id` varchar(128) NOT NULL,
`Name` varchar(256) NOT NULL,
PRIMARY KEY (`Id`)
);
CREATE TABLE `AspNetUsers` (
`Id` varchar(128) NOT NULL,
`Email` varchar(256) DEFAULT NULL,
`NormalizedEmail` varchar(256) DEFAULT NULL,
`EmailConfirmed` tinyint NOT NULL,
`PasswordHash` longtext,
`SecurityStamp` longtext,
`PhoneNumber` longtext,
`PhoneNumberConfirmed` tinyint NOT NULL,
`TwoFactorEnabled` tinyint NOT NULL,
`LockoutEndDateUtc` datetime DEFAULT NULL,
`LockoutEnabled` tinyint NOT NULL,
`AccessFailedCount` int NOT NULL,
`UserName` varchar(256) NOT NULL,
`NormalizedUserName` varchar(256) NOT NULL,
`ConcurrencyStamp` longtext,
`CustomTag` longtext,
`LockoutEnd` datetime,
PRIMARY KEY (`Id`)
);
CREATE TABLE `AspNetUserClaims` (
`Id` int NOT NULL AUTO_INCREMENT,
`UserId` varchar(128) NOT NULL,
`ClaimType` longtext,
`ClaimValue` longtext,
PRIMARY KEY (`Id`),
UNIQUE KEY `Id` (`Id`),
KEY `UserId` (`UserId`),
CONSTRAINT `ApplicationUser_Claims` FOREIGN KEY (`UserId`) REFERENCES `AspNetUsers` (`Id`) ON DELETE CASCADE ON UPDATE NO ACTION
);
CREATE TABLE `AspNetUserLogins` (
`LoginProvider` varchar(128) NOT NULL,
`ProviderKey` varchar(128) NOT NULL,
`UserId` varchar(128) NOT NULL,
PRIMARY KEY (`LoginProvider`,`ProviderKey`,`UserId`),
KEY `ApplicationUser_Logins` (`UserId`),
CONSTRAINT `ApplicationUser_Logins` FOREIGN KEY (`UserId`) REFERENCES `AspNetUsers` (`Id`) ON DELETE CASCADE ON UPDATE NO ACTION
);
CREATE TABLE `AspNetUserRoles` (
`UserId` varchar(128) NOT NULL,
`RoleId` varchar(128) NOT NULL,
PRIMARY KEY (`UserId`,`RoleId`),
KEY `IdentityRole_Users` (`RoleId`),
CONSTRAINT `ApplicationUser_Roles` FOREIGN KEY (`UserId`) REFERENCES `AspNetUsers` (`Id`) ON DELETE CASCADE ON UPDATE NO ACTION,
CONSTRAINT `IdentityRole_Users` FOREIGN KEY (`RoleId`) REFERENCES `AspNetRoles` (`Id`) ON DELETE CASCADE ON UPDATE NO ACTION
);
CREATE TABLE `AspNetUserTokens` (
?????
);
Much thanks!
CREATE TABLE [dbo].[AspNetUserTokens] (
[UserId] NVARCHAR (450) NOT NULL,
[LoginProvider] NVARCHAR (450) NOT NULL,
[Name] NVARCHAR (450) NOT NULL,
[Value] NVARCHAR (MAX) NULL,
CONSTRAINT [PK_AspNetUserTokens] PRIMARY KEY CLUSTERED ([UserId] ASC, [LoginProvider] ASC, [Name] ASC)
);
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.
This question already has answers here:
MySQL Creating tables with Foreign Keys giving errno: 150
(20 answers)
Closed 4 years ago.
I am currently coding a booking system for a company and they also wanted a task managment system but I have encountered an error which is driving me insane.
Executing SQL script in server
ERROR: Error 1215: Cannot add foreign key constraint
SQL Code:
-- -----------------------------------------------------
-- Table `bvsv_system`.`task`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `bvsv_system`.`task` (
`idtask` INT(11) NOT NULL,
`attGora` VARCHAR(200) NULL,
`status` VARCHAR(45) NULL,
`to` VARCHAR(45) NULL,
`jobstatus_id` INT(11) NOT NULL,
`worker_personnummer` VARCHAR(45) NOT NULL,
PRIMARY KEY (`idtask`, `jobstatus_id`, `worker_personnummer`),
INDEX `fk_task_jobstatus1_idx` (`jobstatus_id` ASC),
INDEX `fk_task_worker1_idx` (`worker_personnummer` ASC),
CONSTRAINT `fk_task_jobstatus1`
FOREIGN KEY (`jobstatus_id`)
REFERENCES `bvsv_system`.`jobstatus` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_task_worker1`
FOREIGN KEY (`worker_personnummer`)
REFERENCES `bvsv_system`.`worker` (`personnummer`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
SQL script execution finished: statements: 15 succeeded, 1 failed
I get this error when i try to add a foreign key linking these two tables
CREATE TABLE IF NOT EXISTS `bvsv_system`.`worker` (
`personnummer` VARCHAR(45) NOT NULL,
`fornamn` VARCHAR(45) NULL DEFAULT NULL,
`efternamn` VARCHAR(45) NULL DEFAULT NULL,
`extraanstalld` VARCHAR(45) NOT NULL,
PRIMARY KEY (`personnummer`))
ENGINE = InnoDB
DEFAULT CHARACTER SET = latin1;
and
CREATE TABLE IF NOT EXISTS `bvsv_system`.`task` (
`idtask` INT(11) NOT NULL,
`attGora` VARCHAR(200) NULL,
`status` VARCHAR(45) NULL,
`to` VARCHAR(45) NULL,
`jobstatus_id` INT(11) NOT NULL,
`worker_personnummer` VARCHAR(45) NOT NULL,
PRIMARY KEY (`idtask`, `jobstatus_id`, `worker_personnummer`),
INDEX `fk_task_jobstatus1_idx` (`jobstatus_id` ASC),
INDEX `fk_task_worker1_idx` (`worker_personnummer` ASC),
CONSTRAINT `fk_task_jobstatus1`
FOREIGN KEY (`jobstatus_id`)
REFERENCES `bvsv_system`.`jobstatus` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_task_worker1`
FOREIGN KEY (`worker_personnummer`)
REFERENCES `bvsv_system`.`worker` (`personnummer`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
Help would be much appreciated my fellow coders! :)
The foreign key and primary key need to have the exact same definition. The worker table defines DEFAULT CHARACTER SET = latin1.
I'm not sure why you would want different character sets for different tables. I would recommend just using the database default.
If you do need them, then make the character sets compatible. You can do this at the column level:
CREATE TABLE IF NOT EXISTS `task` (
`idtask` INT(11) NOT NULL,
`attGora` VARCHAR(200) NULL,
`status` VARCHAR(45) NULL,
`to` VARCHAR(45) NULL,
`jobstatus_id` INT(11) NOT NULL,
`worker_personnummer` VARCHAR(45) CHARACTER SET latin1 NOT NULL,
PRIMARY KEY (`idtask`, `jobstatus_id`, `worker_personnummer`),
INDEX `fk_task_jobstatus1_idx` (`jobstatus_id` ASC),
INDEX `fk_task_worker1_idx` (`worker_personnummer` ASC),
CONSTRAINT `fk_task_worker1`
FOREIGN KEY (`worker_personnummer`)
REFERENCES `worker` (`personnummer`)
ON DELETE NO ACTION
ON UPDATE NO ACTION
)
ENGINE = InnoDB
I need a fresh pair of eyes to see what exactly I am doing wrong here.
CREATE TABLE IF NOT EXISTS `spring_normalize`.`users` (
`username` VARCHAR(60) NOT NULL,
`password` VARCHAR(80) NULL,
`authority` VARCHAR(45) NULL,
`name` VARCHAR(100) NULL,
`enabled` TINYINT(1) NULL,
`email` VARCHAR(60) NULL,
PRIMARY KEY (`username`))
ENGINE = InnoDB;
CREATE TABLE IF NOT EXISTS `spring_normalize`.`offers` (
`id` INT NOT NULL AUTO_INCREMENT,
`text` VARCHAR(100) NULL,
`users_username` VARCHAR(60) NOT NULL,
PRIMARY KEY (`id`, `users_username`),
INDEX `fk_offers_users_idx` (`users_username` ASC),
CONSTRAINT `fk_offers_users`
FOREIGN KEY (`users_username`)
REFERENCES `spring_normalize`.`users` (`username`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
From other people who has the same problem:
Is Db InnoDB? Yes
Are all tables InnoDB ? Yes
Is unique index present on referencing table ? Yes
Are referenced and referencing column exactly of the same type ? Yes
Question what do am I doing wrong? Thanks in advance!
As the others stated in comments, your queries are correct
Couple of things you can try :
Select your database first and remove it from your 2 create table
USE `spring_normalize`;
CREATE TABLE IF NOT EXISTS `users` (
`username` VARCHAR(60) NOT NULL,
`password` VARCHAR(80) NULL,
`authority` VARCHAR(45) NULL,
`name` VARCHAR(100) NULL,
`enabled` TINYINT(1) NULL,
`email` VARCHAR(60) NULL,
PRIMARY KEY (`username`))
ENGINE = InnoDB;
CREATE TABLE IF NOT EXISTS `offers` (
`id` INT NOT NULL AUTO_INCREMENT,
`text` VARCHAR(100) NULL,
`users_username` VARCHAR(60) NOT NULL,
PRIMARY KEY (`id`, `users_username`),
INDEX `fk_offers_users_idx` (`users_username` ASC),
CONSTRAINT `fk_offers_users`
FOREIGN KEY (`users_username`)
REFERENCES `users` (`username`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
Try to specify this before the create tables in case the engine would (weirdly) try to create the table offers before users:
-- Do not check foreign key constraints
SET FOREIGN_KEY_CHECKS = 0;
and finally if nothing solves it, do this after having received the error, it will give you more info
SHOW ENGINE INNODB STATUS;
I'm using MySQL workbench to design a database. Server is mysql 5.5.6
I've defined a few foreign keys linking the "candidates" table to the "countries" table. I get this error:
Executing SQL script in server
ERROR: Error 1005: Can't create table 'customer.candidats' (errno: 150)
The thing is: i'm referencing twice the countries table: once for the "nationality" column, once for the user address's country of origin. Is that allowed? Is this the right way to do it?
Here is the generated code that seems to trigger the issue.
CREATE TABLE IF NOT EXISTS `customer`.`candidats` (
`id` INT NOT NULL AUTO_INCREMENT,
`nom` VARCHAR(40) NULL,
`prenom` VARCHAR(40) NULL,
`qualite` ENUM('0001','0002') NULL COMMENT '0001 = Madame\n0002 = Monsieur',
`sexe` SET('1','2') NULL COMMENT '1 = Femme\n2 = Homme',
`date_de_naissance` DATE NULL,
`Nationalite` INT NOT NULL,
`selor_bilinguisme` TINYINT(1) NULL,
`rue` VARCHAR(60) NULL,
`numero` VARCHAR(10) NULL,
`pays` INT NOT NULL,
`region` INT NOT NULL,
`localité` VARCHAR(40) NULL,
`code_postal` VARCHAR(10) NULL,
`email` VARCHAR(241) NULL,
`tel_domicile` VARCHAR(30) NULL,
`tel_bureau` VARCHAR(30) NULL,
`tel_mobile` VARCHAR(30) NULL,
`tel_prefere` ENUM('01','02','03') NULL DEFAULT '03',
PRIMARY KEY (`id`),
INDEX `fk_candidats_pays_idx` (`Nationalite` ASC, `pays` ASC),
INDEX `fk_candidats_régions1_idx` (`region` ASC),
CONSTRAINT `fk_candidats_pays`
FOREIGN KEY (`Nationalite` , `pays`)
REFERENCES `customer`.`pays` (`id` , `id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_candidats_régions1`
FOREIGN KEY (`region`)
REFERENCES `customer`.`régions` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
The "pays" table ("countries" in French)
CREATE TABLE IF NOT EXISTS `customer`.`pays` (
`id` INT NOT NULL AUTO_INCREMENT,
`nom_fr` VARCHAR(45) NULL,
`nom_nl` VARCHAR(45) NULL,
`nationalite_fr` VARCHAR(45) NULL,
`nationalite_nl` VARCHAR(45) NULL,
PRIMARY KEY (`id`),
UNIQUE INDEX `id_UNIQUE` (`id` ASC))
ENGINE = InnoDB
Your schema generator doesn't work correctly.
It should generate:
CONSTRAINT `fk_candidats_pays`
FOREIGN KEY (`pays`)
REFERENCES `customer`.`pays` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_candidats_Nationalite`
FOREIGN KEY (`Nationalite`)
REFERENCES `customer`.`pays` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
To your other question: This type of referencing seems strange when you see it the first time, but it's quite normal and I think there is no other way of constructing this type of relationship.