foreign key not working properly - mysql

I am trying to establish a relationship between two tables using phpMyAdmin. But I am having some trouble of doing this.
I have the foreign key set up but for some reason it dos not add the id of the other table. I am very new to MySQL and can't figure this one out.
Here is my table structure:
tblanswers
CREATE TABLE IF NOT EXISTS `tblanswers` (
`answerid` int(11) NOT NULL AUTO_INCREMENT,
`userid` int(11) DEFAULT NULL,
`cid` int(11) DEFAULT NULL,
`questionid` int(11) NOT NULL,
`answerA` varchar(255) NOT NULL,
`answerB` varchar(255) NOT NULL,
`answerC` varchar(255) NOT NULL,
`comment` varchar(255) NOT NULL,
PRIMARY KEY (`answerid`),
UNIQUE KEY `cid` (`cid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=210 ;
credentials
CREATE TABLE IF NOT EXISTS `credentials` (
`cid` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`second_name` varchar(255) NOT NULL,
`phone` varchar(255) NOT NULL,
`email` varchar(255) NOT NULL,
PRIMARY KEY (`cid`),
KEY `cid` (`cid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=106 ;
I am very unclear how to set foreign keys and how they are connect the tables I looked up couple of tutorials but they did not really explain much in detail.

add this on table tblanswers
CONSTRAINT tb_FK FOREIGN KEY (cid) REFERENCES credentials (cid)
SQLFiddle Demo

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 table creation Error Code: 1005 in this specific case

I have tried everything in solving this issue and yes I know that this type of question is already asked here but I could not solve my issue
It is mysql database
Error Code: 1005
Can't create table '.\project\comments.frm' (errno: 150)
the foreign keys are matching in structure (i.e length and type) then what can be the possible problem in the table creation
Table which is giving error is comments:
CREATE TABLE `comments`(
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`description` VARCHAR(100) NOT NULL,
`user_id` INT(10) UNSIGNED NOT NULL,
`post_id` INT(10) UNSIGNED NOT NULL,
FOREIGN KEY (`post_id`) REFERENCES `posts`.`id`,
FOREIGN KEY (`user_id`) REFERENCES `users`.`id`,
PRIMARY KEY (`id`)
) ENGINE=INNODB DEFAULT CHARSET=latin1;`
Here is posts table which is already created in the databas
CREATE TABLE `posts` (
`id` int(10) unsigned NOT NULL auto_increment,
`title` varchar(30) default NULL,
`description` longtext,
`image` varchar(50) default NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Here is the users table which is also already created in the database
CREATE TABLE `users` (
`id` int(10) unsigned NOT NULL auto_increment,
`user_name` varchar(33) default NULL,
`email` varchar(255) NOT NULL,
`password` varchar(255) default NULL,
`type` varchar(255) NOT NULL,
`registrationDate` date NOT NULL,
PRIMARY KEY (`id`,`email`,`type`)
)
Your syntax is incorrect. The REFERENCES keyword should be followed by table (columns):
CREATE TABLE `comments`(
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`description` VARCHAR(100) NOT NULL,
`user_id` INT(10) UNSIGNED NOT NULL,
`post_id` INT(10) UNSIGNED NOT NULL,
FOREIGN KEY (`post_id`) REFERENCES `posts` (`id`),
FOREIGN KEY (`user_id`) REFERENCES `users` (`id`),
PRIMARY KEY (`id`)
) ENGINE=INNODB DEFAULT CHARSET=latin1;

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.