#1452 - Cannot add or update a child row: a foreign key constraint fails ... Jutts - mysql

I have created tables in MySQL Workbench as shown below :
Categories Table
CREATE TABLE IF NOT EXISTS `categories` (
`categoryId` int(11) primary key auto_incremnt NOT NULL,
`categoryName` varchar(200) DEFAULT NULL,
`categoryDescription` varchar(200) DEFAULT NULL,
`categoryPicture` varchar(100) DEFAULT NULL,
`PostDate` varchar(255) NOT NULL,
`status` varchar(10) NOT NULL DEFAULT '1',
`LastInsertID` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=45 ;
Products Table
CREATE TABLE IF NOT EXISTS `products` (
`proId` int(11) NOT NULL,
CONSTRAINT `categoryId` FOREIGN KEY (`categoryId`) REFERENCES `categories` (`categoryId`) ,
`proName` varchar(100) DEFAULT NULL,
`proPath` varchar(90) DEFAULT NULL,
`proPrice` float DEFAULT NULL,
`proQuantity` decimal(38,0) DEFAULT NULL,
`proImage` varchar(100) DEFAULT NULL,
`PostDate` varchar(50) NOT NULL,
`status` int(11) NOT NULL DEFAULT '1'
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;
I'm having a bit of a strange problem, I'm trying to add a foreign key
to one table that references another, but it is failing for some
reason. With my limited knowledge of MySQL, the only thing that could
possibly be suspect is that there is a foreign key on a different
table referencing the one I am trying to reference.
Please help me out as soon as possible .
Thanks in advance

You should create the categoryId column before assigning it in a foreign key,
categoryId int(11) NOT NULL,

CREATE TABLE IF NOT EXISTS `products` (
`proId` INT(11) NOT NULL,
`categoryId` INT ,
`proName` VARCHAR(100) DEFAULT NULL,
`proPath` VARCHAR(90) DEFAULT NULL,
`proPrice` FLOAT DEFAULT NULL,
`proQuantity` DECIMAL(38,0) DEFAULT NULL,
`proImage` VARCHAR(100) DEFAULT NULL,
`PostDate` VARCHAR(50) NOT NULL,
`status` INT(11) NOT NULL DEFAULT '1',
FOREIGN KEY (`categoryId`) REFERENCES `categories` (`categoryId`)
) ENGINE=INNODB DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;

Related

Trouble getting my primary and foreign key to work

I keep getting errors when I try to run the relational part of the database to pull the 3 columns in the relation table from the customer table and bill table.
DROP DATABASE IF EXISTS CreateDB2;
CREATE DATABASE CreateDB2;
USE CreateDB2;
CREATE TABLE `tbl_employee` (
`tbl_EmployeeName` varchar(20) NOT NULL,
`tbl_Department` varchar(15) NOT NULL,
`employee_id` int(11) NOT NULL AUTO_INCREMENT,
`department_location` varchar(20) NOT NULL,
`department_name` varchar(15) NOT NULL,
`supervisor` varchar(15) NOT NULL,
PRIMARY KEY (`employee_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE `customer` (
`c_ID` varchar(15) NOT NULL,
`c_address` varchar(50) NOT NULL,
`c_Time` time NOT NULL,
`c_order` int(100) NOT NULL,
PRIMARY KEY (`c_ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE `bill` (
`b_items` double DEFAULT NULL,
`b_price` double DEFAULT NULL,
`b_discount` double DEFAULT NULL,
`b_deliveryFee` double DEFAULT NULL,
`b_tax` double DEFAULT NULL,
`b_tip` double DEFAULT NULL,
`b_total` double NOT NULL,
`quantity` int(11) NOT NULL,
PRIMARY KEY (`b_total`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE `food` (
`code` int(11) NOT NULL AUTO_INCREMENT,
`f_catagory` varchar(20) NOT NULL,
`f_item` varchar(10) NOT NULL,
`f_info` varchar(50) NOT NULL,
`f_price` int(11) NOT NULL,
PRIMARY KEY (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE `restaurantinfo` (
`name` varchar(20) NOT NULL,
`address` varchar(50) DEFAULT NULL,
`phone` int(13) DEFAULT NULL,
`email` varchar(20) DEFAULT NULL,
PRIMARY KEY (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE `relationaltable` (
`c_ID` varchar(15) NOT NULL,
`c_order` int(100) NOT NULL,
`b_total` double NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
ALTER TABLE `customer` ADD CONSTRAINT `c_ID` FOREIGN KEY (`c_ID`) REFERENCES `relationaltable`(`c_ID`) ON DELETE RESTRICT ON UPDATE RESTRICT;
ALTER TABLE `order` ADD CONSTRAINT `c_order` FOREIGN KEY (`c_order`) REFERENCES `relationaltable`(`c_order`) ON DELETE RESTRICT ON UPDATE RESTRICT;
ALTER TABLE `bill` ADD CONSTRAINT `b_total` FOREIGN KEY (`b_total`) REFERENCES `relationaltable`(`b_total`) ON DELETE RESTRICT ON UPDATE RESTRICT;
On the last part here, it is not working. It gives error code 1005
The alter table at the bottom is the probably the issue. I am just not sure how to fix it. Any help is appreciated. Thanks.
The foreign key is incorrectly formed.
You connect customer.c_ID should be equal to relationaltable.c_order
customer.c_ID is varchar(15) NOT NULL
relationaltable.c_order is int(100) NOT NULL
The data type and also the length has to be matching

MySQL Error Number 150 when creating Table with Foreign Key

I am having an issue creating a new table in my database. I've seen that the error code it is returning is to do with Foreign Key constraints.
I checked to ensure that the data type of the foreign key in the new table matched the data type of the primary key in the other table. They are both int(11).
However I am still getting an error. Am I missing something? This is my SQL script for creating the new table:
CREATE TABLE `regular_features` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(200) DEFAULT NULL,
`day` VARCHAR(200) DEFAULT NULL,
`description` TEXT DEFAULT NULL,
`programme_id` INT(11) NOT NULL,
PRIMARY KEY (`id`),
FOREIGN KEY (`programme_id`) REFERENCES directoryprogramme(id)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
This is the original table containing the primary key:
CREATE TABLE `directoryprogramme` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(250) NOT NULL,
`broadcast_time` VARCHAR(100) NOT NULL,
`description` TEXT NOT NULL,
`days` VARCHAR(150) NOT NULL,
`contributors` VARCHAR(250) NOT NULL,
`directorycompany_id` INT(11) NOT NULL,
`directorycontact_id` VARCHAR(250) NOT NULL,
`facebook_link` VARCHAR(250) DEFAULT NULL,
`twitter_link` VARCHAR(250) DEFAULT NULL,
`wikipedia_link` VARCHAR(250) DEFAULT NULL,
`web` VARCHAR(250) DEFAULT NULL,
`imageextension` VARCHAR(10) DEFAULT NULL,
`type` VARCHAR(20) NOT NULL DEFAULT 'other',
PRIMARY KEY (`id`)
) ENGINE=MYISAM AUTO_INCREMENT=1161 DEFAULT CHARSET=utf8;
The Foreign Key will be the id of directoryprogramme
The problem is the last line of your create statement:
ENGINE=INNODB DEFAULT CHARSET=utf8;
You mix MYISAM in ald table with INNODB in your new table.
That doesn't work.
Chnage the engine in your new table to MYISAM and it works.

MySQL table creation

Below is the code I used in MySQL workbench to create the database as well as the tables. Finally I have mentioned the error I face. Could anyone please help me with this?
delimiter $$
CREATE DATABASE `sa38team4` /*!40100 DEFAULT CHARACTER SET utf8 */$$
Employee Table :
delimiter $$
CREATE TABLE `employee` (
`EmpID` int(11) NOT NULL AUTO_INCREMENT,
`EmpName` varchar(100) NOT NULL,
`DOB` datetime NOT NULL,
`Gender` varchar(10) NOT NULL,
`Password` varchar(50) NOT NULL,
`ContactNumber` varchar(45) NOT NULL,
`Email` varchar(45) DEFAULT NULL,
`Role` varchar(15) NOT NULL,
`Address` varchar(200) DEFAULT NULL,
PRIMARY KEY (`EmpID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8$$
Inventory Table :
delimiter $$
CREATE TABLE `inventory` (
`ItemID` int(11) NOT NULL AUTO_INCREMENT,
`PID` int(11) NOT NULL,
`TotalQty` int(11) NOT NULL,
`Availability` int(11) NOT NULL,
`ReorderPt` int(11) NOT NULL,
`MinOrdQty` int(11) NOT NULL,
`UnitPrice` decimal(10,2) NOT NULL,
PRIMARY KEY (`ItemID`),
KEY `PID` (`PID`),
CONSTRAINT `PID` FOREIGN KEY (`PID`) REFERENCES `productdetail` (`PID`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8$$
`MID` varchar(45) NOT NULL,
`Manufacturer` varchar(100) NOT NULL,
`Model` varchar(45) NOT NULL,
`PartNo` varchar(45) NOT NULL,
`ItemDesc` varchar(100) NOT NULL,
PRIMARY KEY (`PID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8$$
Product Details Table :
delimiter $$
CREATE TABLE `productdetail` (
`PID` int(11) NOT NULL AUTO_INCREMENT,
`MID` varchar(45) NOT NULL,
`Manufacturer` varchar(100) NOT NULL,
`Model` varchar(45) NOT NULL,
`PartNo` varchar(45) NOT NULL,
`ItemDesc` varchar(100) NOT NULL,
PRIMARY KEY (`PID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8$$
Trans In Table :
delimiter $$
CREATE TABLE `transin` (
`TransID` int(11) NOT NULL AUTO_INCREMENT,
`Date` datetime NOT NULL,
`EmpID` int(11) NOT NULL,
`ItemID` int(11) NOT NULL,
`Qty` int(11) NOT NULL,
`UnitPrice` decimal(10,2) NOT NULL,
`Remark` varchar(100) DEFAULT NULL,
PRIMARY KEY (`TransID`),
KEY `EmpID` (`EmpID`),
KEY `ItemID` (`ItemID`),
CONSTRAINT `EmpID` FOREIGN KEY (`EmpID`) REFERENCES `employee` (`EmpID`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `ItemID` FOREIGN KEY (`ItemID`) REFERENCES `inventory` (`ItemID`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8$$
All the four above tables are created.
TransOut Tablle :
delimiter $$
CREATE TABLE `transout` (
`TransID` int(11) NOT NULL AUTO_INCREMENT,
`Date` datetime NOT NULL,
`EmpID` int(11) NOT NULL,
`ItemID` int(11) NOT NULL,
`Qty` int(11) NOT NULL,
`UnitPrice` decimal(10,2) NOT NULL,
`Remark` varchar(100) DEFAULT NULL,
PRIMARY KEY (`TransID`),
KEY `EmpID` (`EmpID`),
KEY `ItemID` (`ItemID`),
CONSTRAINT `EmpID` FOREIGN KEY (`EmpID`) REFERENCES `employee` (`EmpID`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `ItemID` FOREIGN KEY (`ItemID`) REFERENCES `inventory` (`ItemID`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8$$
The last table n creation, shows an error as
"Error Code : 1005. Can't create table 'sa38team4.transout'(errno: 121)"
Could anyone please help me?
Check out this post : MySQL errorno 121
As said :
Check that all your constraints are really spelled out correctly, also check that there's not any other tables that uses the constraint names ItemID or EmpID
So I think that you may use another name into your TransOut table for ItemID & EmpID

What Is Possible Use One Reference Field To Multiple Foreign Key Constraint

I want to make 3 Tables like this :
wc_groups Table
CREATE TABLE IF NOT EXISTS `wc_groups` (
`id` int(2) unsigned NOT NULL AUTO_INCREMENT,
`idgroup` int(7) NOT NULL,
`title` varchar(10) NOT NULL,
`content` text,
`status` smallint(1) NOT NULL DEFAULT '1',
PRIMARY KEY (`id`),
UNIQUE KEY `idgroup` (`idgroup`),
KEY `status` (`status`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
wc_matches Table
CREATE TABLE IF NOT EXISTS `wc_matches` (
`id` int(4) unsigned NOT NULL AUTO_INCREMENT,
`time` date NOT NULL,
`group_id` int(2) unsigned NOT NULL,
`place` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
`team_id_1` int(10) unsigned NOT NULL,
`team_id_2` int(10) unsigned NOT NULL,
`edituser` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`id`),
KEY `group_id_foreign` (`group_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;
wc_teams Table
CREATE TABLE IF NOT EXISTS `wc_teams` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`title` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`group_id` int(2) unsigned NOT NULL,
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;
ALTER TABLE `wc_teams`
ADD CONSTRAINT `group_id_foreign` FOREIGN KEY (`group_id`) REFERENCES `wc_groups` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;
Why i got an error when execution Code to create table wc_team ?
What's possible to use What Is Possible Use One Reference Field ( wc_groups (id) ) To Multiple Foreign Key Constraint ?
I don't understand what you mean with multiple foreign keys.
But the problem in your wc_teams create query is that you have a lost , behind
`group_id` int(2) unsigned NOT NULL,
But you also miss your primary key so i guess you need this
CREATE TABLE IF NOT EXISTS `wc_teams` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`title` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`group_id` int(2) unsigned NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;

Importing a database schema from a SQL DUMP

I have the following database schema that has a bunch of tables and foreign keys, when i try to import the sql dump i keep getting the following errors.
Can't create table errno 150
I understand that it is trying to create tables with dependencies of tables that are not created yet but i don't understand how to import the schema without butchering out all of the foreign keys and then re-creating them per the answers given on Stack and google.
There has to be an easier way, what do big companies do that have hundreds of tables?
I have the sql statements below and any suggestions would be appreciated. Thanks
#
# Encoding: Unicode (UTF-8)
#
DROP TABLE IF EXISTS `contact_interest`;
DROP TABLE IF EXISTS `contact_seeking`;
DROP TABLE IF EXISTS `interests`;
DROP TABLE IF EXISTS `job_current`;
DROP TABLE IF EXISTS `job_desired`;
DROP TABLE IF EXISTS `job_listings`;
DROP TABLE IF EXISTS `my_contacts`;
DROP TABLE IF EXISTS `profession`;
DROP TABLE IF EXISTS `seeking`;
DROP TABLE IF EXISTS `status`;
DROP TABLE IF EXISTS `zip_code`;
CREATE TABLE `contact_interest` (
`contact_id` int(10) unsigned NOT NULL,
`interest_id` int(10) unsigned NOT NULL,
KEY `mycontacts_contactinterest_fk` (`contact_id`),
KEY `interests_contactinterest_fk` (`interest_id`),
CONSTRAINT `mycontacts_contactinterest_fk` FOREIGN KEY (`contact_id`) REFERENCES `my_contacts` (`contact_id`),
CONSTRAINT `interests_contactinterest_fk` FOREIGN KEY (`interest_id`) REFERENCES `interests` (`interest_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `contact_seeking` (
`contact_id` int(10) unsigned NOT NULL,
`seeking_id` int(10) unsigned NOT NULL,
KEY `contactid_contactseeking_fk` (`contact_id`),
KEY `seeking_contactseeking_fk` (`seeking_id`),
CONSTRAINT `contactid_contactseeking_fk` FOREIGN KEY (`contact_id`) REFERENCES `my_contacts` (`contact_id`),
CONSTRAINT `seeking_contactseeking_fk` FOREIGN KEY (`seeking_id`) REFERENCES `seeking` (`seeking_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `interests` (
`interest_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`interest` varchar(50) DEFAULT NULL,
PRIMARY KEY (`interest_id`)
) ENGINE=InnoDB AUTO_INCREMENT=25 DEFAULT CHARSET=latin1;
CREATE TABLE `job_current` (
`contact_id` int(10) unsigned NOT NULL,
`title` varchar(20) DEFAULT NULL,
`salary` decimal(8,2) DEFAULT NULL,
`start_date` date DEFAULT NULL,
KEY `mycontacts_jobcurrent_fk` (`contact_id`),
CONSTRAINT `mycontacts_jobcurrent_fk` FOREIGN KEY (`contact_id`) REFERENCES `my_contacts` (`contact_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `job_desired` (
`contact_id` int(10) unsigned NOT NULL,
`title` varchar(20) DEFAULT NULL,
`salary_low` decimal(8,2) DEFAULT NULL,
`salary_high` decimal(8,2) DEFAULT NULL,
`available` date DEFAULT NULL,
`years_exp` int(11) DEFAULT NULL,
KEY `mycontacts_jobdesired_fk` (`contact_id`),
CONSTRAINT `mycontacts_jobdesired_fk` FOREIGN KEY (`contact_id`) REFERENCES `my_contacts` (`contact_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `job_listings` (
`job_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`title` varchar(25) DEFAULT NULL,
`salary` decimal(8,2) DEFAULT NULL,
`zip_code` char(5) DEFAULT NULL,
`description` varchar(50) DEFAULT NULL,
PRIMARY KEY (`job_id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=latin1;
CREATE TABLE `my_contacts` (
`contact_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`last_name` varchar(30) DEFAULT NULL,
`first_name` varchar(20) DEFAULT NULL,
`phone` char(10) DEFAULT NULL,
`email` varchar(50) DEFAULT NULL,
`gender` char(1) DEFAULT NULL,
`birthday` date DEFAULT NULL,
`prof_id` int(11) unsigned NOT NULL,
`status_id` int(10) unsigned NOT NULL,
`zip_code` char(5) DEFAULT NULL,
PRIMARY KEY (`contact_id`),
KEY `profession_mycontacts_fk` (`prof_id`),
KEY `zipcode_mycontacts_fk` (`zip_code`),
KEY `status_my_contacts_fk` (`status_id`),
CONSTRAINT `profession_mycontacts_fk` FOREIGN KEY (`prof_id`) REFERENCES `profession` (`prof_id`),
CONSTRAINT `status_my_contacts_fk` FOREIGN KEY (`status_id`) REFERENCES `status` (`status_id`),
CONSTRAINT `zipcode_mycontacts_fk` FOREIGN KEY (`zip_code`) REFERENCES `zip_code` (`zip_code`)
) ENGINE=InnoDB AUTO_INCREMENT=17 DEFAULT CHARSET=latin1;
CREATE TABLE `profession` (
`prof_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`profession` varchar(30) DEFAULT NULL,
PRIMARY KEY (`prof_id`)
) ENGINE=InnoDB AUTO_INCREMENT=16 DEFAULT CHARSET=latin1;
CREATE TABLE `seeking` (
`seeking_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`seeking` varchar(40) DEFAULT NULL,
PRIMARY KEY (`seeking_id`)
) ENGINE=InnoDB AUTO_INCREMENT=17 DEFAULT CHARSET=latin1;
CREATE TABLE `status` (
`status_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`status` varchar(30) DEFAULT NULL,
PRIMARY KEY (`status_id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=latin1;
CREATE TABLE `zip_code` (
`zip_code` char(5) NOT NULL DEFAULT '',
`city` varchar(20) DEFAULT NULL,
`state` char(2) DEFAULT NULL,
PRIMARY KEY (`zip_code`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
I found that I only needed two lines to fix my issue, I added one 0 at the top and 1 at the bottom and I was good. Sorry to waste your time...
SET FOREIGN_KEY_CHECKS = 0;
SET FOREIGN_KEY_CHECKS = 1;
the easiest way would be to do it via commandline like this:
mysql db_name < backup-file.sql
this executes your sql file in one transaction. If you execute your stuff in one transaction then you won't get the foreign key errors.