Cannot add foreign key constraint MySql Error - mysql

i've a school project and i'm trying to execute my sql script and i've this error
1215 - Cannot add foreign key constraint
Here's my table who generate this error:
CREATE TABLE IF NOT EXISTS `Visiteur` (
`id` char(4) NOT NULL,
`nom` char(30) DEFAULT NULL,
`prenom` char(30) DEFAULT NULL,
`login` char(20) DEFAULT NULL,
`mdp` char(20) DEFAULT NULL,
`adresse` char(30) DEFAULT NULL,
`cp` char(5) DEFAULT NULL,
`ville` char(30) DEFAULT NULL,
`dateEmbauche` date DEFAULT NULL,
`idRang` char(2)NOT NULL,
PRIMARY KEY (`id`),
FOREIGN KEY (`idRang`) REFERENCES Rang(`idRang`)
) ENGINE=InnoDB;
And here my references table:
CREATE TABLE IF NOT EXISTS `Rang` (
`idRang` char(2) NOT NULL,
`nomRang` char(15) NOT NULL,
PRIMARY KEY (`idRang`)
) ENGINE=InnoDB;
Sorry for my english, i'm french
Thanks in advance

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

Error code: 1824 Failed to open the refernced table [table exists]

I'm trying to add a foreign key constraint, but I'm getting [Error Code: 1824: Failed to open the refrenced table 'agent_agent']
the table agent_agent exists in my database, I can't get my head around this issue.
I tried creating the constraint using the graphical mode of mysql workbench and I'm getting the same error.
select * from agent_agent; return the data, so the table exists in the DB but:
ALTER TABLE demande_contact
ADD CONSTRAINT dddd
FOREIGN KEY (agent_id_id) REFERENCES agent_agent(id);
is returning an error 1824.
Edit: Here's the 2 tables DDL
CREATE TABLE `agent_agent` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`matricule` varchar(6) NOT NULL,
`nom_et_prenom` varchar(60) NOT NULL,
`fonction` varchar(60) NOT NULL,
`structure` varchar(60) NOT NULL,
`poste_org` varchar(60) DEFAULT NULL,
`metier` varchar(3) DEFAULT NULL,
`csp` varchar(20) DEFAULT NULL,
`en_activite` tinyint(1) NOT NULL,
`timestamp` datetime(6) NOT NULL,
`updated` datetime(6) NOT NULL,
`user_id` int(11) NOT NULL,
`service` varchar(60) DEFAULT NULL,
`centre_cout` varchar(10) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `agent_agent_user_id_bfcb5c50` (`user_id`)
) ENGINE=MyISAM AUTO_INCREMENT=628 DEFAULT CHARSET=utf8
CREATE TABLE `demande_contact` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`telephone` varchar(40) NOT NULL,
`agent_id_id` int(11) NOT NULL,
`demande_id_id` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `demande_contact_demande_id_id_0abc00b0_fk_demande_d` (`demande_id_id`),
KEY `agent_id_id_constraint_idx` (`agent_id_id`),
CONSTRAINT `demande_contact_demande_id_id_0abc00b0_fk_demande_d` FOREIGN KEY (`demande_id_id`) REFERENCES `demande_demandetransport` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

Best normalised practice to map phone numbers with user or office

I am designing a DB in MySQL. I have a user table, office table and a phone number table as I intend to allow multiple phone numbers to a user or for an office. so I know I need to add foreign keys in phone number table to office table and to user table rather than the other way round. But how do I do it without a null record?
What is the best-normalized way to make this with neither officeId not userId in the phone number record null?
MY Phone number table
CREATE TABLE `phonenumber` (
`Id` varchar(36) NOT NULL,
`Title` varchar(100) DEFAULT NULL,
`UserId` varchar(36) DEFAULT NULL,
`SchoolId` int(11) DEFAULT NULL,
`CreatedOn` datetime NOT NULL,
`ModifiedOn` datetime NOT NULL,
`CreatedBy` varchar(36) NOT NULL,
`ModifiedBy` varchar(36) NOT NULL,
`Number` varchar(20) NOT NULL,
PRIMARY KEY (`Id`),
KEY `FK_Phone_User` (`UserId`),
KEY `FK_Phone_School` (`SchoolId`),
CONSTRAINT `FK_Phone_School` FOREIGN KEY (`SchoolId`) REFERENCES `school` (`Id`),
CONSTRAINT `FK_Phone_User` FOREIGN KEY (`UserId`) REFERENCES `user` (`Id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
My User Table
CREATE TABLE `user` (
`Id` varchar(36) NOT NULL,
`UserName` varchar(20) NOT NULL,
`DisplayName` varchar(100) DEFAULT NULL,
`OfficialName` varchar(100) DEFAULT NULL,
`PasswordHash` varchar(50) DEFAULT NULL,
`CreatedOn` datetime DEFAULT NULL,
`CreatedBy` varchar(36) DEFAULT NULL,
`ModifiedOn` datetime DEFAULT NULL,
`ModifiedBy` varchar(36) DEFAULT NULL,
PRIMARY KEY (`Id`),
UNIQUE KEY `UserName` (`UserName`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
My School table
CREATE TABLE `school` (
`Id` int(11) NOT NULL AUTO_INCREMENT,
`Name` varchar(100) NOT NULL,
`AddressId` varchar(36) DEFAULT NULL,
`CreatedOn` datetime NOT NULL,
`ModifiedOn` datetime NOT NULL,
`CreatedBy` varchar(36) NOT NULL,
`ModifiedBy` varchar(36) NOT NULL,
PRIMARY KEY (`Id`),
KEY `FK_School_Address` (`AddressId`),
CONSTRAINT `FK_School_Address` FOREIGN KEY (`AddressId`) REFERENCES `address` (`Id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
You simply have to allow for NULL fields during the creation of the Phone_numbers table. What you were warned against is having a whole record with NULLs. You are correctly handling the field that but not saying anything or saying NULL. Here's an example:
CREATE TABLE Phone_numbers(
phone_number VARCHAR(15) NOT NULL,
user_id INT UNSIGNED,
office_id INT UNSIGNED,
PRIMARY KEY (phone_number),
CONSTRAINT RefUsers1 FOREIGN KEY (user_id)
REFERENCES Users(user_id),
CONSTRAINT RefOffices2 FOREIGN KEY (office_id)
REFERENCES Offices(office_id)
)ENGINE=INNODB
;
For this simple model

mySQL - Unable to Insert Values to Table

I am trying to insert a data to my database table using sql queries. I receive this error when updating,
INSERT INTO `permohonan_cuti` (`permohonan_id`, `baki_cuti_permohonan`, `tarikh_mohon`, `tarikh_mula`, `tarikh_akhir`, `sokongan`, `pengganti`, `tujuan`, `kelulusan`, `pelulus`, `staff_id`, `cuti_id`, `katCuti_id`)
VALUES
(1603, 8, '2017-03-29 16:50:24', '2017-04-04', '0000-00-00', 'Dalam Proses', '39', 'HAL PERIBADI', 'Dalam Proses', NULL, 91, 88, 1),
(1604, 19, '2017-03-29 20:28:12', '2017-03-29', '0000-00-00', 'Dalam Proses', '132', 'DEMAM,BATUK,SELSEMA', 'Lulus', '378078', 141, 138, 5)
MySQL said: Documentation
#1452 - Cannot add or update a child row: a foreign key constraint fails (`ktmbcp_staff`.`permohonan_cuti`, CONSTRAINT `permohonan_cuti_ibfk_1` FOREIGN KEY (`staff_id`) REFERENCES `staff` (`staff_id`) ON DELETE CASCADE ON UPDATE CASCADE)
May I know what cause the problem and how to fix it? Are my tables correct?
Below are the tables,
CREATE TABLE `permohonan_cuti` (
`permohonan_id` int(11) NOT NULL,
`baki_cuti_permohonan` float DEFAULT NULL,
`tarikh_mohon` datetime NOT NULL,
`tarikh_mula` date DEFAULT NULL,
`tarikh_akhir` date DEFAULT NULL,
`sokongan` varchar(50) DEFAULT NULL,
`pengganti` varchar(50) DEFAULT NULL,
`tujuan` varchar(100) NOT NULL,
`kelulusan` varchar(50) DEFAULT NULL,
`pelulus` varchar(10) DEFAULT NULL,
`staff_id` int(11) NOT NULL,
`cuti_id` int(11) NOT NULL,
`katCuti_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
ALTER TABLE `permohonan_cuti`
ADD CONSTRAINT `permohonan_cuti_ibfk_1` FOREIGN KEY (`staff_id`) REFERENCES `staff` (`staff_id`),
ADD CONSTRAINT `permohonan_cuti_ibfk_2` FOREIGN KEY (`cuti_id`) REFERENCES `cuti` (`cuti_id`) ON DELETE CASCADE,
ADD CONSTRAINT `permohonan_cuti_ibfk_3` FOREIGN KEY (`katCuti_id`) REFERENCES `kat_cuti` (`katCuti_id`);
ALTER TABLE `permohonan_cuti`
ADD PRIMARY KEY (`permohonan_id`),
ADD KEY `staff_id` (`staff_id`),
ADD KEY `cuti_id` (`cuti_id`),
ADD KEY `katCuti_id` (`katCuti_id`);
CREATE TABLE `staff` (
`staff_id` int(11) NOT NULL,
`staff_no` varchar(8) NOT NULL,
`ic_no` varchar(20) NOT NULL,
`nama` varchar(50) NOT NULL,
`j_id` int(11) DEFAULT NULL,
`tarikh_khidmat` date DEFAULT NULL,
`gred_id` int(11) DEFAULT NULL,
`l_id` varchar(50) DEFAULT NULL,
`email` varchar(50) DEFAULT NULL,
`no_tel` varchar(12) DEFAULT NULL,
`no_hp` varchar(12) DEFAULT NULL,
`alamat` varchar(100) DEFAULT NULL,
`no_akaun` int(15) DEFAULT NULL,
`no_kwsp` varchar(15) DEFAULT NULL,
`password` varchar(10) NOT NULL,
`nama_waris` varchar(50) DEFAULT NULL,
`tel_waris` varchar(12) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
ALTER TABLE `staff`
ADD CONSTRAINT `staff_ibfk_3` FOREIGN KEY (`j_id`) REFERENCES `jabatan` (`j_id`),
ADD CONSTRAINT `staff_ibfk_4` FOREIGN KEY (`gred_id`) REFERENCES `gred_pekerja` (`gred_id`);
ALTER TABLE `staff`
ADD PRIMARY KEY (`staff_id`),
ADD KEY `j_id` (`j_id`),
ADD KEY `gred_id` (`gred_id`);
The message is pretty clear, you are trying to add a staff_id that doesn't exist in the staff table.

cannot add second FK : got error can't create table'.jobstatus\#sql-32c_12f2f.frm' (errno:150)

CREATE TABLE `job` (
`jobId` int(11) NOT NULL auto_increment,
`jobcode` varchar(25) default NULL,
`jobname` varchar(255) default NULL,
`location` varchar(255) default NULL,
`budget` int(10) unsigned default NULL,
`year_type` varchar(100) default NULL,
`worklineId` int(11) default NULL,
PRIMARY KEY (`jobId`),
KEY `NewIndex` (`worklineId`),
FOREIGN KEY (`worklineId`) REFERENCES `workline` (`worklineId`)
) TYPE=InnoDB;
CREATE TABLE `subjob` (
`subjobId` int(11) NOT NULL auto_increment,
`subjobcode` varchar(25) default NULL,
`subjobname` varchar(255) default NULL,
`subjobbudget` int(11) unsigned default NULL,
`jobgoal_date` date default '0000-00-00',
`jobId` int(11) default NULL,
PRIMARY KEY (`subjobId`),
KEY `NewIndex` (`jobId`),
FOREIGN KEY (`jobId`) REFERENCES `job` (`jobId`)
) TYPE=InnoDB;
CREATE TABLE `contract` (
`contractId` int(11) NOT NULL auto_increment,
`contractcode` varchar(25) default NULL,
`price` int(11) unsigned default NULL,
`contractprice` int(11) unsigned default NULL,
`company` varchar(50) default NULL,
`signdate` date default '0000-00-00',
`begindate` date default '0000-00-00',
`enddateplan` date default '0000-00-00',
`note` text,
PRIMARY KEY (`contractId`)
) TYPE=InnoDB;
CREATE TABLE `subjob_contract` (
`subjobcontractId` int(11) NOT NULL auto_increment,
`status` varchar(11) default NULL,
`contractId` int(11) default NULL,
`subjobId` int(11) default NULL,
PRIMARY KEY (`subjobcontractId`),
KEY `NewIndex` (`contractId`),
KEY `NewIndex2` (`subjobId`),
FOREIGN KEY (`contractId`) REFERENCES `contract` (`contractId`)
) TYPE=InnoDB
I m using mysql front 3.2 to manage database,I can add first fk but when i add second fk i got an error following this :
sql execution error #1005. response from the database: can't create table'.jobstatus#sql-32c_12f2f.frm' (errno:150). i already define the new index for fk subjobId reference to subjob table what could be the possibility of this error? thank you
Check the datatype and size of the subjobId column on primary table and referenced table. both must be same than it will allow you to create foreign key.
Answer is: You can not refer that column/table which is not created yet. Try to execute tables having foreign keys after the referenced tables.
Obviously you should have consistency in datatypes of foreign key and referenced column as well
Correct Execution Demo. Also You should use Engine=InnoDB instead of Type=InnoDB