mysql foreign keys - mysql

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.

Related

Cannot create 2 foreign key

I tried to create 2 foreign keys in customerdetails table but it keeps me showing an error when I execute this query. Is there any problem with my query?
CREATE TABLE `vg_shippingdb`.`customerdetails` (
`CustomerID` INT NOT NULL AUTO_INCREMENT ,
`Name` VARCHAR(25) NOT NULL ,
`Age` INT NOT NULL ,
`Sex` VARCHAR(10) NOT NULL ,
`Email` VARCHAR(45) NOT NULL ,
PRIMARY KEY (`CustomerID`),
FOREIGN KEY (ReservedID) REFERENCES reservationdetails(ReservedID),
FOREIGN KEY (TicketID) REFERENCES ticket(TicketID)) ENGINE = InnoDB;
CREATE TABLE `vg_shippingdb`.`reservationdetails` (
`ReservedID` INT NOT NULL AUTO_INCREMENT ,
`ReservedDate` DATE NOT NULL ,
`DepartureTime` VARCHAR(25) NOT NULL ,
`Destination` VARCHAR(45) NOT NULL ,
`Accommodation` TEXT NULL ,
`NameOfVessel` VARCHAR(45) NOT NULL ,
PRIMARY KEY (`ReservedID`)) ENGINE = InnoDB;
CREATE TABLE `vg_shippingdb`.`ticket` (
`TicketID` INT NOT NULL AUTO_INCREMENT ,
`TicketNo` VARCHAR(25) NOT NULL ,
`Status` VARCHAR(25) NOT NULL ,
PRIMARY KEY (`TicketID`)) ENGINE = InnoDB;
The columns does not exist in a table really. Specifying the foreign key does not create a column, you must do it explicitly before the FK definition.
CREATE TABLE `vg_shippingdb`.`customerdetails` (
`CustomerID` INT NOT NULL AUTO_INCREMENT ,
`Name` VARCHAR(25) NOT NULL ,
`Age` INT NOT NULL ,
`Sex` VARCHAR(10) NOT NULL ,
`Email` VARCHAR(45) NOT NULL ,
PRIMARY KEY (`CustomerID`),
-- Create columns
ReservedID INT,
TicketID INT,
-- Then use them in FK expressions
FOREIGN KEY (ReservedID) REFERENCES reservationdetails(ReservedID),
FOREIGN KEY (TicketID) REFERENCES ticket(TicketID)) ENGINE = InnoDB;
PS. The table which FK is refferred on must be created firstly - FK cannot refer the table which will be created later.
before creating foreign keys, create all tables
First create reservationdetails and ticket then create customerdetails.
Note: First create source/referred table then create table with FOREIGN KEY

MYSQL Error 1064 in Primary and Unique Keys

Good day. I am trying to add a suppliers table on my database and when i try to save, it throws this error.
1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '0) NOT NULL , PRIMARY KEY (supp_id), UNIQUE supp_name (supp_name))' at line 1
I have attached my SQL statement.
CREATE TABLE `project_inv`.`suppliers` (
`supp_id` INT(11) NOT NULL AUTO_INCREMENT ,
`supp_name` VARCHAR(255) NOT NULL ,
`supp_addr` VARCHAR(300) NOT NULL ,
`supp_phone` INT(20) NOT NULL ,
`supp_email` VARCHAR(255) NOT NULL ,
`supp_notes` VARCHAR(1000) NOT NULL ,
`status` ENUM(0) NOT NULL ,
PRIMARY KEY (`supp_id`),
UNIQUE `supp_name` (`supp_name`)
) ENGINE = InnoDB;
I think its something with my UNIQUE key but i really can't figure out what the error is. Any form of help will be appreciated. Thanks
It is not about the PRIMARY or UNIQUE declaration, but about ENUM(): it expects string literals, so you would need to surround the values in the list with single quotes:
CREATE TABLE `project_inv`.`suppliers` (
`supp_id` INT(11) NOT NULL AUTO_INCREMENT ,
`supp_name` VARCHAR(255) NOT NULL ,
`supp_addr` VARCHAR(300) NOT NULL ,
`supp_phone` INT(20) NOT NULL ,
`supp_email` VARCHAR(255) NOT NULL ,
`supp_notes` VARCHAR(1000) NOT NULL ,
`status` ENUM('0') NOT NULL ,
PRIMARY KEY (`supp_id`),
UNIQUE `supp_name` (`supp_name`)
) ENGINE = InnoDB;
However having a non-nullable ENUM() column with just one value allowed makes little sense - basically you are forcing every row to have the same value ('0'). So either add more values to the list... or just remove the column.
try like below by using string inside enum i used 'N' instated 0
CREATE TABLE `project_inv`.`suppliers` (
`supp_id` INT(11) NOT NULL AUTO_INCREMENT ,
`supp_name` VARCHAR(255) NOT NULL ,
`supp_addr` VARCHAR(300) NOT NULL ,
`supp_phone` INT(20) NOT NULL ,
`supp_email` VARCHAR(255) NOT NULL ,
`supp_notes` VARCHAR(1000) NOT NULL ,
`status` ENUM('N') NOT NULL ,
PRIMARY KEY (`supp_id`),
UNIQUE `supp_name` (`supp_name`)
) ENGINE = InnoDB;

MYSQL error in creating foreign key constraint

I am using MySQL to create a small database. and facing some issues in foreign keys and primary key. I really don't understand as it seems a simple problem.
CREATE TABLE IF NOT EXISTS `db_trimms`.`urban_area` (
`area_id` INT(10) NOT NULL ,
`city` VARCHAR(60) NOT NULL ,
`state` VARCHAR(60) NOT NULL ,
`urban_area` VARCHAR(60) NOT NULL ,
`census_region` VARCHAR(60) NOT NULL ,
`area_no` VARCHAR(60) NOT NULL ,
`freeway_speed` VARCHAR(60) NOT NULL ,
`arterial_speed` VARCHAR(60) NOT NULL ,
PRIMARY KEY (`area_id`) )
ENGINE = InnoDB
DEFAULT CHARACTER SET = latin1;
its running successfully. But while create another table and creating foreign key referring to the area_id of the above table...its creating issues...
#1005 - Can't create table 'db_trimms.emiss_others_offpeak' (errno: 150) (Details...)
and here is the query
CREATE TABLE IF NOT EXISTS `db_trimms`.`emiss_others_offpeak` (
`area_id` INT(10) UNSIGNED NOT NULL ,
`ammonia` VARCHAR(60) NOT NULL ,
`atm_carbon_dio` VARCHAR(60) NOT NULL ,
`carbon_dio_equiv` VARCHAR(60) NOT NULL ,
`carbon_mono` VARCHAR(60) NOT NULL ,
`methane` VARCHAR(60) NOT NULL ,
`nitrogen_dio` VARCHAR(60) NOT NULL ,
`nitrogen_oxide` VARCHAR(60) NOT NULL ,
`nitrous_oxide` VARCHAR(60) NOT NULL ,
`non_meth_hydrocarbs` VARCHAR(60) NOT NULL ,
`oxides_of_nitrogen` VARCHAR(60) NOT NULL ,
`particulate_matter_pm10` VARCHAR(60) NOT NULL ,
`particulate_matter_pm2_5` VARCHAR(60) NOT NULL ,
`sulfate` VARCHAR(60) NOT NULL ,
` sulfur_dioxide` VARCHAR(60) NOT NULL ,
`total_hydrocarbon` VARCHAR(60) NOT NULL ,
`vol_org_comp` VARCHAR(60) NOT NULL ,
PRIMARY KEY (`area_id`) ,
CONSTRAINT `fk_others_offpeak_urban`
FOREIGN KEY (`area_id` )
REFERENCES `db_trimms`.`urban_area` (`area_id` )
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB
DEFAULT CHARACTER SET = latin1;
The data types are incompatible with each other. Make column area_id from table urban_area also UNSIGNED.
`area_id` INT(10) UNSIGNED NOT NULL ,
SQLFiddle Demo

Can't create table in MySQL [error 150] when use foreign key

I have designed schema with MySQL workbench.
But it couldn't complete Database Synchronize.It can create tables with out foreign keys.
I copied SQL from MySQL WorkBench to execute in phpmysqadmin.
CREATE TABLE IF NOT EXISTS `Books`.`Users` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT ,
`mail` VARCHAR(45) NOT NULL ,
`password` VARCHAR(45) NOT NULL ,
`smspassword` VARCHAR(8) NULL ,
`mobile` VARCHAR(16) NULL ,
`type` ENUM('admin','secretery','groupadmin','user') NOT NULL DEFAULT 'user' ,
`securelogin` ENUM('true','false') NULL DEFAULT 'true' ,
PRIMARY KEY (`id`) ,
UNIQUE INDEX `id_UNIQUE` (`id` ASC) ,
UNIQUE INDEX `mail_UNIQUE` (`mail` ASC) )
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_unicode_ci
COMMENT = 'Table to store users data'
Users table created successfully. But following table (Profile) can't be created.
CREATE TABLE IF NOT EXISTS `Books`.`Profiles` (
`id` INT NOT NULL AUTO_INCREMENT ,
`firstname` VARCHAR(45) NOT NULL ,
`lastname` VARCHAR(45) NOT NULL ,
`title` VARCHAR(45) NOT NULL ,
`nationalcode` VARCHAR(45) NOT NULL ,
`User_id` INT NOT NULL ,
PRIMARY KEY (`id`, `User_id`) ,
INDEX `fk_Profiles_Users` (`User_id` ASC) ,
CONSTRAINT `fk_Profiles_Users`
FOREIGN KEY (`User_id` )
REFERENCES `Books`.`Users` (`id` )
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_unicode_ci
But it will be return:
#1005 - Can't create table 'Books.Profiles' (errno: 150)
Where is the problem, and how should I solve this?
You need to match the primary id column type with the foreign key column type - your primary id in Users is UNSIGNED INT, but your foreign key in Profiles is INT. Try this:
CREATE TABLE IF NOT EXISTS `Books`.`Profiles` (
`id` INT NOT NULL AUTO_INCREMENT ,
`firstname` VARCHAR(45) NOT NULL ,
`lastname` VARCHAR(45) NOT NULL ,
`title` VARCHAR(45) NOT NULL ,
`nationalcode` VARCHAR(45) NOT NULL ,
`User_id` INT UNSIGNED NOT NULL , -- <<= Check the type here!
PRIMARY KEY (`id`, `User_id`) ,
INDEX `fk_Profiles_Users` (`User_id` ASC) ,
CONSTRAINT `fk_Profiles_Users`
FOREIGN KEY (`User_id` )
REFERENCES `Books`.`Users` (`id` )
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_unicode_ci;

sql error errno: 121

CREATE TABLE `users` (
`UID` INT UNSIGNED NOT NULL AUTO_INCREMENT ,
`username` VARCHAR(45) NOT NULL ,
`password` VARCHAR(100) NULL ,
`name` VARCHAR(100) NULL ,
`gender` BIT NULL ,
`email` VARCHAR(255) NULL ,
`phone` VARCHAR(30) NOT NULL ,
`verified` BIT NOT NULL DEFAULT 0 ,
`time_zone` INT NULL ,
`time_register` DATETIME NULL ,
`time_active` DATETIME NULL ,
PRIMARY KEY (`UID`) ,
UNIQUE INDEX `username_UNIQUE` (`username` ASC) ,
INDEX `verified_INDEX` (`verified` ASC) )
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8;
-- -----------------------------------------------------
-- Table `companies`
-- -----------------------------------------------------
CREATE TABLE `companies` (
`CID` INT UNSIGNED NOT NULL AUTO_INCREMENT ,
`name` VARCHAR(45) NOT NULL ,
`address` VARCHAR(100) NULL ,
`email` VARCHAR(255) NULL ,
`phone` VARCHAR(30) NULL ,
`link` TEXT NULL ,
`image_small` TEXT NULL ,
`image_large` TEXT NULL ,
`yahoo` VARCHAR(100) NULL ,
`linkin` VARCHAR(100) NULL ,
`twitter` VARCHAR(20) NULL ,
`description` TEXT NULL ,
`shoutout` VARCHAR(140) NULL ,
`verified` BIT NOT NULL DEFAULT 0 ,
PRIMARY KEY (`CID`) ,
INDEX `name_INDEX` (`name` ASC) ,
INDEX `verified_INDEX` (`verified` ASC) )
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8;
-- -----------------------------------------------------
-- Table `products`
-- -----------------------------------------------------
CREATE TABLE `products` (
`PID` INT UNSIGNED NOT NULL AUTO_INCREMENT ,
`CID` INT UNSIGNED NOT NULL ,
`name` VARCHAR(100) NULL ,
`description` TEXT NULL ,
`image_small` TEXT NULL ,
`image_large` TEXT NULL ,
`tag` VARCHAR(45) NULL ,
`price` DECIMAL(11,2) NULL ,
PRIMARY KEY (`PID`) ,
INDEX `tag_INDEX` (`tag` ASC) ,
INDEX `company.cid_FK` (`CID` ASC) ,
CONSTRAINT `company.cid_FK`
FOREIGN KEY (`CID` )
REFERENCES `companies` (`CID` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8;
-- -----------------------------------------------------
-- Table `users_companies`
-- -----------------------------------------------------
CREATE TABLE `users_companies` (
`UID` INT UNSIGNED NOT NULL ,
`CID` INT UNSIGNED NOT NULL ,
`role` INT UNSIGNED NULL ,
PRIMARY KEY (`CID`, `UID`) ,
INDEX `users.uid_FK` (`UID` ASC) ,
INDEX `company.cid_FK` (`CID` ASC) ,
CONSTRAINT `users.uid_FK`
FOREIGN KEY (`UID` )
REFERENCES `users` (`UID` )
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `company.cid_FK`
FOREIGN KEY (`CID` )
REFERENCES `companies` (`CID` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8;
i got error
#1005 - Can't create table 'wew.users_companies' (errno: 121) (Details...)
can anyone tell me which one is the problem ?
You have two constraints called company.cid_FK. Rename one.
For errors like this, you can find more information with 'perror'. i.e.
shell $ perror 121
MySQL error code 121: Duplicate key on write or update
Win32 error code 121: The semaphore timeout period has expired.
I got the same error MySQL error code 121: Duplicate key on write or update.
although I deleted the table from my database to recreated again but I could not so I recreated the table yet with different constrain.
I found that the old constrain is still there.