Hello I have two mysql tables one that holds username and password second that holds user information. Here are the tables:
CREATE TABLE IF NOT EXISTS `test`.`dbo.users` (
`userId` INT(11) NOT NULL AUTO_INCREMENT ,
`userUsername` VARCHAR(45) NULL ,
`userPassword` VARCHAR(45) NULL ,
`dbo.userProfiles_userProfileId` INT(11) NOT NULL ,
PRIMARY KEY (`userId`, `dbo.userProfiles_userProfileId`) ,
INDEX `fk_dbo.users_dbo.userProfiles` (`dbo.userProfiles_userProfileId` ASC) ,
CONSTRAINT `fk_dbo.users_dbo.userProfiles`
FOREIGN KEY (`dbo.userProfiles_userProfileId` )
REFERENCES `test`.`dbo.userProfiles` (`userId` )
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB;
CREATE TABLE IF NOT EXISTS `test`.`dbo.userProfiles` (
`userProfileId` INT(11) NOT NULL AUTO_INCREMENT ,
`userId` INT(11) NOT NULL ,
`userFirstName` VARCHAR(45) NULL ,
`userMidleName` VARCHAR(45) NULL ,
`userLastName` VARCHAR(45) NULL ,
`userBirthDate` VARCHAR(45) NULL ,
`userCountry` VARCHAR(45) NULL ,
`userState` VARCHAR(45) NULL ,
`userCity` VARCHAR(45) NULL ,
`userZipCode` VARCHAR(45) NULL ,
`userPrimaryAddress` VARCHAR(45) NULL ,
`userSecondaryAddress` VARCHAR(45) NULL ,
`userThirdAddress` VARCHAR(45) NULL ,
`userFirstPhone` VARCHAR(45) NULL ,
`userSecondaryPhone` VARCHAR(45) NULL ,
`userThirdPhone` VARCHAR(45) NULL ,
`userFirstEmail` VARCHAR(45) NULL ,
`userSecondaryEmail` VARCHAR(45) NULL ,
`userThirdEmail` VARCHAR(45) NULL ,
`userDescription` VARCHAR(45) NULL ,
PRIMARY KEY (`userProfileId`, `userId`) )
ENGINE = InnoDB;
My problem with this tables is that the fk key doesn’t work and I’m not sure why I’m missing something here.. ( I haven’t used foreign keys much).
Error:
Executing SQL script in server
ERROR: Error 1005: Can’t create table ‘test.dbo.users’ (errno: 150)
Can you please help fixing this so I can use fk on this tables and others? and if you got some time to spare to explain me how fk keys work exactly (using mysql workbench to create them on a diagram then forward engineer). thank you for your help
You have to create the root tables first (userProfiles). You can temporarily bypass this restriction by disabling foreign key checks with
set foreign_key_checks=0. This must be done if you’re creating multiple tables with circular references.