mysql one to many relation is not working - mysql

Having some trouble adding a relation between tables
CREATE TABLE IF NOT EXISTS `employees` (
`emp_id` int(11) NOT NULL auto_increment,
`emp_fname` char(50) NOT NULL,
`emp_sname` char(50) NOT NULL,
`emp_patr` char(50) NOT NULL,
`emp_birth` datetime NOT NULL default CURRENT_TIMESTAMP,
`isInCharge` boolean default NULL,
`depart_id` int(11) NOT NULL,
PRIMARY KEY (`emp_id`)
) ENGINE=InnoDB DEFAULT CHARSET=cp1251;
CREATE TABLE IF NOT EXISTS `department` (
`depart_id` int(11) NOT NULL auto_increment,
`depart_name` char(50) NOT NULL,
PRIMARY KEY (`depart_id`),
FOREIGN KEY (depart_id) REFERENCES employees (depart_id) on delete
cascade on update cascade
) ENGINE=InnoDB DEFAULT CHARSET=cp1251;
Cannot add foreign key constraint
What is going wrong? I need to make possible for many employees to be in one department.
Also, how can I generate a random birth date from 1950 to 1990?

Your foreign key is in the wrong place. It belongs in the employees table not the department table. And it should be:
FOREIGN KEY (depart_id) REFERENCES department(depart_id) on delete cascade on update cascade
This should be easy to remember. You define the primary key in the table where the column is unique. You define the foreign key in all tables that refer to that primary key.

It should be the other way around right? dept_Id in Employee shall be foriegn key referencing the primary key Dept_ID of Department.

Related

MySQL #1452 - Cannot add or update a child row

I'm begginer here, all what i'm trying to do is insert into a table field which is a foreign key, please take a look at this two tables :
Table Categorie
CREATE TABLE IF NOT EXISTS `categorie` (
`id_cat` int(2) NOT NULL AUTO_INCREMENT,
`nom_cat` varchar(20) NOT NULL,
PRIMARY KEY (`id_cat`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
and table Annonce
CREATE TABLE IF NOT EXISTS `annonce` (
`id_annonce` int(6) NOT NULL AUTO_INCREMENT,
`titre` varchar(30) NOT NULL,
`description` varchar(255) NOT NULL,
`tarif` float NOT NULL,
`deplacement` int(2) NOT NULL,
`date_creation` date NOT NULL,
`date_expiration` date NOT NULL,
`image` varchar(255) NOT NULL,
`id_cat` int(2) DEFAULT NULL,
PRIMARY KEY (`id_annonce`),
KEY `id_cat` (`id_cat`),
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
After linking the foreign key id_cat manually (ON UPDATE SET NULL ON DELETE CASCADE) that's how the db looks like
and after inserting data into Categorie table it looks like this
But unfortunately i couldn't execute this query :
INSERT INTO annonce (id_annonce, titre, description, tarif, deplacement,
date_creation, date_expiration,id_cat)
VALUES('','anything','anything',2,3,'2017-04-01','2017-04-01',2)
the error says :
1452 - Cannot add or update a child row: a foreign key constraint fails
(lametcom.annonce, CONSTRAINT annonce_ibfk_2 FOREIGN KEY (id_cat)
REFERENCES annonce (id_cat) ON DELETE SET NULL ON UPDATE CASCADE)
Can anyone help please and so sorry about my poor English i hope you can understand what i mean
Your foreign key constraint is wrong. You have
FOREIGN KEY id_cat REFERENCES annonce (id_cat)
but it should be:
FOREIGN KEY id_cat REFERENCES categorie (id_cat)
The table name in the foreign key constraint has to be the table you're linking to.

Cannot add or update a child row: a foreign key constraint fails mysql

CREATE TABLE `class` (
`class_id` int(11) NOT NULL AUTO_INCREMENT,
`section_name` varchar(50) NOT NULL,
`class_alias` varchar(200) NOT NULL,
`grading_scheme` int(11) NOT NULL DEFAULT '0',
`year` year(4) NOT NULL,
`grade_calc_method_id` varchar(20) DEFAULT NULL,
PRIMARY KEY (`class_id`)
) ENGINE=InnoDB AUTO_INCREMENT=48819 DEFAULT CHARSET=latin1;
CREATE TABLE `teachers` (
`teacher_id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`teacher_subject` varchar(20) NOT NULL DEFAULT 'None',
PRIMARY KEY (`teacher_id`),
KEY `user_id` (`user_id`,`school_id`)
) ENGINE=InnoDB AUTO_INCREMENT=48606 DEFAULT CHARSET=latin1;
CREATE TABLE `teacher_classes` (
`teacher_class_id` int(11) NOT NULL AUTO_INCREMENT,
`teacher_id` int(11) NOT NULL,
`class_id` int(11) NOT NULL,
PRIMARY KEY (`teacher_class_id`),
UNIQUE KEY `teacher_id_class_id` (`teacher_id`,`class_id`),
KEY `teacher_id` (`teacher_id`,`class_id`)
) ENGINE=InnoDB AUTO_INCREMENT=46707 DEFAULT CHARSET=latin1;
Trying to insure data consistency between the tables by using foreign key so that the DBMS can check for errors.I have another junction table teacher_classes
Here is my query to add foreign keys constraint
ALTER TABLE teacher_classes
ADD CONSTRAINT `tc_fk_class_id` FOREIGN KEY (`class_id`)
REFERENCES class (`class_id`) ON UPDATE NO ACTION ON DELETE NO ACTION,
ADD CONSTRAINT `tc_fk_teacher_id` FOREIGN KEY (`teacher_id`)
REFERENCES teachers (`teacher_id`) ON UPDATE NO ACTION ON DELETE NO ACTION;
've seen the other posts on this topic, but no luck, getting following error.
Cannot add or update a child row: a foreign key constraint fails
(DB_NAME.#sql-403_12, CONSTRAINT
tc_fk_teacher_id FOREIGN KEY (teacher_id) REFERENCES teachers
(teacher_id) ON DELETE NO ACTION ON UPDATE NO ACTION)
Too late to Answer. I just had the same problem the solution is easy.
You're getting this error because you're trying to or UPDATE a row to teacher_classes doesn't match the id in table teachers.
A simple solution is disable foreign key checks before performing any operation on the table.
SET FOREIGN_KEY_CHECKS = 0;
After you are done with the table enable it again.
SET FOREIGN_KEY_CHECKS = 1;
Or you can remove not null constraint and insert a NULL value in it.
That's most probably the column definition doesn't match properly. For table teachers the PK column definition is as below.
`teacher_id` int(11) NOT NULL AUTO_INCREMENT
Make sure you have the same definition in your child table teacher_classes

how to use foreign key for auto-incremented records?

DROP TABLE IF EXISTS `student`;
CREATE TABLE `student` (
`student_id` int(11) NOT NULL AUTO_INCREMENT,
`student_name` varchar(45) DEFAULT NULL,
PRIMARY KEY (`student_id`)
) ENGINE=InnoDB AUTO_INCREMENT=901840505 DEFAULT CHARSET=utf8;
DROP TABLE IF EXISTS `grades`;
CREATE TABLE `grades` (
`grade_id` int(11) NOT NULL AUTO_INCREMENT,
`student_id` int(11) DEFAULT NULL,
`grade` varchar(45) DEFAULT NULL,
PRIMARY KEY (`grade_id`),
KEY `stdgrd_idx` (`student_id`),
CONSTRAINT `stdgrd` FOREIGN KEY (`student_id`) REFERENCES `student` (`student_id`)
ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=1641 DEFAULT CHARSET=utf8;
I have created two tables student and grade. In order to send the auto-incremented values ofstudent_id to grade(student_id) table I established a foreign key between those two records as follows:
CONSTRAINT `stdgrd` FOREIGN KEY (`student_id`) REFERENCES `student`
(`student_id`) ON DELETE CASCADE ON UPDATE CASCADE
My question is when I insert values into student_name record in the student table the student(student_id) is auto-incremented so I want the auto-incremented value to be sent to grade(student_id)
but the grade table is not taking the value in. I already tried with the help of questions posted in stackoverflow but I couldn't make it. Please can anyone help out with this issue??
The Foreign Key relationship is only intended to validate the content of the child column. There is no automatic transfer of data. Inserting into student and thus generating the student_id auto_inc value will have no immediate impact on the grades table. That merely creates a student_id value that is now an acceptable content for the grades.student_id column.

Mysql create table with multiple foreign key on delete set null

I am trying to create a database with multiple foreign keys with delete/ update constraints, but I got a error code 1005 with following sql scripts:
CREATE TABLE Worker (
WorkerID smallint auto_increment,
WorkerType varchar(45) NOT NULL,
WorkerName varchar(45) NOT NULL,
Position varchar(45) NOT NULL,
TaxFileNumber int NOT NULL,
Address varchar(100) ,
Phone varchar(20) ,
SupervisorID smallint ,
PRIMARY KEY (WorkerID),
FOREIGN KEY (SupervisorID) REFERENCES Worker(WorkerID)
ON DELETE SET NULL
ON UPDATE CASCADE
)Engine=InnoDB;
CREATE TABLE Grape (
GrapeID smallint NOT NULL,
GrapeType varchar(45) NOT NULL,
JuiceConversionRatio int,
StorageContainer ENUM('Stainless Steel Tank','Oak Barrel'),
AgingRequirement int,
PRIMARY KEY (GrapeID)
)Engine=InnoDB;
CREATE TABLE Vineyard (
VineyardID smallint auto_increment,
VineyardName VARCHAR(45) NOT NULL,
FarmerID smallint NOT NULL,
GrapeID smallint NOT NULL,
ComeFrom varchar(45) NOT NULL,
HarvestedAmount int,
RipenessPercent int,
PRIMARY KEY (VineyardID),
FOREIGN KEY (FarmerID) REFERENCES Worker(WorkerID)
ON DELETE SET NULL
ON UPDATE CASCADE,
FOREIGN KEY (GrapeID) REFERENCES Grape(GrapeID)
ON DELETE SET NULL
ON UPDATE CASCADE
)Engine=InnoDB;
The error code says that fail to create the Vineyard table, I just want to know the proper format for creating multiple foreign keys with delete/update control.
Your foreign key rule is ON DELETE SET NULL but your column definition is NOT NULL.
Either change your column definition and remove the NOT NULL part or overthink your foreign key rule. That works:
CREATE TABLE Vineyard (
VineyardID smallint auto_increment,
VineyardName VARCHAR(45) NOT NULL,
FarmerID smallint,
GrapeID smallint,
ComeFrom varchar(45) NOT NULL,
HarvestedAmount int,
RipenessPercent int,
PRIMARY KEY (VineyardID),
FOREIGN KEY (FarmerID) REFERENCES Worker(WorkerID)
ON DELETE SET NULL
ON UPDATE CASCADE,
FOREIGN KEY (GrapeID) REFERENCES Grape(GrapeID)
ON DELETE SET NULL
ON UPDATE CASCADE
)Engine=InnoDB;
SQLFiddle demo
Try with create table(innoDB enginer) without foreign key and use the update table with constraint syntax, for example:
ALTER TABLE `vineyard`
ADD CONSTRAINT `relation_farmer_has_many_vineyards`
FOREIGN KEY (`farmer_id`)
REFERENCES `worker` (`worker_id`)
ON DELETE SET NULL
ON UPDATE CASCADE;
Reference:
http://dev.mysql.com/doc/refman/5.6/en/innodb-foreign-key-constraints.html
Trick: is not recommended to use capital letters(or camel case) in the names of the tables that the behavior differs from the operating system being used:
http://dev.mysql.com/doc/refman/5.1/en/identifier-case-sensitivity.html
Visit :
https://developer.android.com/training/basics/data-storage/databases.html#DefineContract
Cursor c = db.query(
FeedEntry.TABLE_NAME, // The table to query
projection, // The columns to return
selection, // The columns for the WHERE clause
selectionArgs, // The values for the WHERE clause
null, // don't group the rows
null, // don't filter by row groups
sortOrder // The sort order
);
Visit :
http://dev.mysql.com/doc/refman/5.5/en/innodb-foreign-key-constraints.html
CREATE TABLE `ffxi_characterJob` (
`serverID` int(11) NOT NULL,
`userid` int(10)unsigned NOT NULL,
`characterName` varchar(255) NOT NULL,
`jobAbbr` char(4) NOT NULL,
`jobLevel` int(11) default '0',
PRIMARY KEY (`serverID`,`userid`,`characterName`,`jobAbbr`),
INDEX (`jobAbbr`),
CONSTRAINT FOREIGN KEY (`serverID`,`userid`,`characterName`) REFERENCES `ffxi_characters` (`serverID`,`userid`,`characterName`)
ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT FOREIGN KEY (`jobAbbr`) REFERENCES `ffxi_jobType` (`jobAbbr`) ON DELETE CASCADE ON UPDATE CASCADE
) TYPE=InnoDB;

Foreign Key not working: Error code 1005, SQL state HY000: Can't create table

I have two tables I have created and I'm adding the foreign key constraint after the fact.
The two tables are defined as such:
CREATE TABLE `user` (
`user_id` int(11) NOT NULL auto_increment,
`user_ad_id` varchar(500) default NULL,
`user_name` varchar(100) NOT NULL,
`login_id` varchar(100) default NULL,
`email` varchar(256) NOT NULL,
`personal_config` int(10) NOT NULL,
PRIMARY KEY (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
and
CREATE TABLE IF NOT EXISTS personal_config (
config_id INT(10) NOT NULL AUTO_INCREMENT,
last_updated TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
configuration TEXT(25600) NOT NULL,
PRIMARY KEY (config_id)
)ENGINE=InnoDB DEFAULT CHARSET=utf8;
ALTER TABLE personal_config ADD CONSTRAINT personal_config_fk_user FOREIGN KEY
(config_id) REFERENCES user(personal_config);
And I keep getting the same error but can't figure it out. I've searched all the related threads to this.
Your FK config_id can't be an autoincrement field, that doesn't make much sense right? That field reflects a value in the foreign table, it cannot be set arbitrarily in the local table.
I think this is what you want:
ALTER TABLE user ADD CONSTRAINT personal_config_fk_user FOREIGN KEY (personal_config) REFERENCES personal_config(config_id);
Your ALTER TABLE statement is backward. Since personal_config.config_id is an auto_increment primary key, the foreign key should be defined in the users table against personal_config, not in personal_config against the users table.
ALTER TABLE users ADD CONSTRAINT user_fk_personal_config
FOREIGN KEY (personal_config)
REFERENCES personal_config(config_id);
if you set your user table field personal_config is primary key then it is possible to execute
CREATE TABLE IF NOT EXISTS personal_config (
config_id INT(10) NOT NULL AUTO_INCREMENT,
last_updated TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
configuration TEXT(25600) NOT NULL,
PRIMARY KEY (config_id), FOREIGN KEY
(config_id) REFERENCES user(personal_config)
)ENGINE=InnoDB DEFAULT CHARSET=utf8;