MYSQL on delete cascade example - mysql

I can't figure out how to use on delete cascade in my example.
CREATE TABLE `users` (
`login` varchar(16) NOT NULL,
`password` varchar(16) NOT NULL,
PRIMARY KEY (`login`),
UNIQUE KEY `login` (`login`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
CREATE TABLE `employees` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`Name` varchar(20) NOT NULL,
`Surname` varchar(25) NOT NULL,
`Birthday` date NOT NULL,
`Adres` varchar(50) NOT NULL,
`Telephone` varchar(25) NOT NULL,
`login` varchar(16) DEFAULT NULL,
PRIMARY KEY (`ID`),
UNIQUE KEY `login` (`login`),
CONSTRAINT `employees_ibfk_1` FOREIGN KEY (`login`) REFERENCES `users` (`login`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
One table stores informations about employee and if he has account(login) there is another table with logins and passwords.
My goals:
Not every employee needs to have user account(that means - unique record in Users table) so Employees.Login shouldn't be restricted with NOT NULL.
I want possiblity to add new user in Users and then assign it to some employee.
When I delete employee, related unique user is also deleted(if he had one).
First two are already done. I don't know how to make 3 happen now.

You've put the CONSTRAINT in the wrong CREATE TABLE statement. It goes on the referencing table, which is "users", because that's the table you want to automatically delete from when a row in the other table is deleted.
You want to put a nullable "ID" in the "users" table, which is unique and a foreign key to "employees".

Use this query :
CREATE TABLE `users` (
`login` varchar(16) NOT NULL,
`password` varchar(16) NOT NULL,
PRIMARY KEY (`login`),
UNIQUE KEY `login` (`login`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `employees` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`Name` varchar(20) NOT NULL,
`Surname` varchar(25) NOT NULL,
`Birthday` date NOT NULL,
`Adres` varchar(50) NOT NULL,
`Telephone` varchar(25) NOT NULL,
`login` varchar(16) DEFAULT NULL,
PRIMARY KEY (`ID`),
UNIQUE KEY `login` (`login`),
CONSTRAINT `employees_ibfk_1` FOREIGN KEY (`login`) REFERENCES `users` (`login`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Based on suggestion from Hammerite now my tables definion looks like this:
CREATE TABLE `employees` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`Name` varchar(20) NOT NULL,
`Surname` varchar(25) NOT NULL,
`Birthday` date NOT NULL,
`Adres` varchar(50) NOT NULL,
`Telephone` varchar(25) NOT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
CREATE TABLE `users` (
`login` varchar(16) NOT NULL,
`password` varchar(16) NOT NULL,
`employee_id` int(11) NOT NULL,
PRIMARY KEY (`login`),
UNIQUE KEY `login` (`login`),
UNIQUE KEY `employee_id` (`employee_id`),
CONSTRAINT `users_ibfk_1` FOREIGN KEY (`employee_id`) REFERENCES `employees` (`ID`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8
I have deleted login column from employees table
I have created another column employee_id in User table. It's unique foreign key and cannot be null since I dont want user accounts that are not used by anybody.
Now If I do this:
INSERT INTO users VALUES('login123','password',2);
then this row will be deleted after I do this:
DELETE FROM employees WHERE id=2;
I was sure that I need to make some reference in employees table to users table, thats why I didn't think about solution like this.
THANKS!

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

Should I use Inner Join in this case?

I am working on a student attendance mini-project, and I don't know how to proceed for my database. I'm new to SQL and databases in general so this might seem dumb to you.
So, I want to do a database containing the table student, which contains : student_id (primary key) , name (string) and attendance(boolean) (that's the bare minimum, i'll add more afterwards) and I want to register the daily attendance of the students. So I want to have all the students tied to every date of the week.
I created a date table in phpMyadmin but I don't know how to proceed to link them, i've tried an Inner Join and it was successful.
The problem is : If i want to add another line to the student table my table won't update, so is there a way to "automatically" tie all the students to the date table ?
Sorry if this seems confused I've tried my best to summarize it !
Lets have some idea about tables should be there to implement a proper Student Attendance system in place. I have copied create script for some of my tables that used for maintaining Students record per course. I hope following sample Table scripts with relation will help you understanding regarding table structure and also to solve your issue.
Please be noted, That this table structures for your your reference only. You can add/remove tables/columns as per your requirement once you get an overall idea from this post.
CREATE TABLE `staff` (
`id` int(11) NOT NULL,
`type` varchar(200) DEFAULT NULL,
`first_name` varchar(200) DEFAULT NULL,
`last_name` varchar(200) DEFAULT NULL,
`emal` varchar(200) DEFAULT NULL,
`contact` varchar(200) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `batch` (
`id` int(11) NOT NULL,
`department` varchar(200) DEFAULT NULL,
`details` varchar(200) DEFAULT NULL,
`staff_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `batch_staff_idx` (`staff_id`),
CONSTRAINT `batch_staff` FOREIGN KEY (`staff_id`) REFERENCES `staff` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `student` (
`id` int(11) NOT NULL,
`batch_id` int(11) DEFAULT NULL,
`first_name` varchar(200) DEFAULT NULL,
`last_name` varchar(200) DEFAULT NULL,
`email` varchar(200) DEFAULT NULL,
`contact` varchar(200) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `batch_student_idx` (`batch_id`),
CONSTRAINT `batch_student` FOREIGN KEY (`batch_id`) REFERENCES `batch` (`batch_id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `course` (
`id` int(11) NOT NULL,
`name` varchar(200) DEFAULT NULL,
`details` varchar(200) DEFAULT NULL,
`staff_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `course_staff_idx` (`staff_id`),
CONSTRAINT `course_staff` FOREIGN KEY (`staff_id`) REFERENCES `staff` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `attendence` (
`course_id` int(11) NOT NULL,
`student_id` int(11) DEFAULT NULL,
`class_date` date DEFAULT NULL,
KEY `att_course_idx` (`course_id`),
KEY `att_student_idx` (`student_id`),
CONSTRAINT `att_course` FOREIGN KEY (`course_id`) REFERENCES `course` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `att_student` FOREIGN KEY (`student_id`) REFERENCES `student` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Your required data will finally store into table Attendance. From this table data, you will be able to find list of students absent/present per date and per course. Remember, the attendance table should enrich daily from a automated OR a manual process.

Foreign key constraint fails with Insert Into Select in MySQL

I'm quite new to SQL, and I'm trying to upload data to my tables. For this I have special tables where I upload the data from a CSV file, and then, from this table, I am trying to copy the data to the final table.
But now I have a problem with an intermediate table where I have uploaded my data. The table is:
CREATE TABLE `_work_has_person` (
`work_id` int(11) NOT NULL,
`person_id` int(11) NOT NULL,
`primary_contribution_id` int(11) DEFAULT NULL,
PRIMARY KEY (`work_id`,`person_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
I want to copy the data in
CREATE TABLE `work_has_person` (
`work_id` int(11) NOT NULL,
`person_id` int(11) NOT NULL,
`primary_contribution_id` int(11) NOT NULL,
PRIMARY KEY (`work_id`,`person_id`),
KEY `fk_work_has_person_person1_idx` (`person_id`),
KEY `fk_work_has_person_work1_idx` (`work_id`),
KEY `fk_work_has_person_primary_contribution1_idx` (`primary_contribution_id`),
CONSTRAINT `fk_work_has_person_person1` FOREIGN KEY (`person_id`) REFERENCES `person` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `fk_work_has_person_primary_contribution1` FOREIGN KEY (`primary_contribution_id`) REFERENCES `primary_contribution` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `fk_work_has_person_work1` FOREIGN KEY (`work_id`) REFERENCES `work` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Which is an intermediate table between:
CREATE TABLE `work` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title_work` varchar(250) DEFAULT NULL,
`subtitle_work` varchar(250) DEFAULT NULL,
`date_work` varchar(45) DEFAULT NULL,
`unix_date_work` varchar(100) DEFAULT NULL,
`sinopsis` text,
`ref_bne` varchar(100) DEFAULT NULL,
`ref_alt` longtext,
`language_id` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `fk_work_language1_idx` (`language_id`),
KEY `title_work` (`title_work`),
CONSTRAINT `fk_work_language1` FOREIGN KEY (`language_id`) REFERENCES `language` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=24610 DEFAULT CHARSET=utf8;
and
CREATE TABLE `person` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(100) NOT NULL,
`img_person` varchar(250) DEFAULT NULL,
`born_date` varchar(45) DEFAULT NULL,
`unix_born_date` varchar(100) DEFAULT NULL,
`city_born_date` varchar(100) DEFAULT NULL,
`country_born_date` varchar(100) DEFAULT NULL,
`death_date` varchar(45) DEFAULT NULL,
`unix_death_date` varchar(100) DEFAULT NULL,
`city_death_date` varchar(100) DEFAULT NULL,
`country_death_date` varchar(45) DEFAULT NULL,
`biography` longtext,
`ref_bne` varchar(100) DEFAULT NULL,
`ref_alt` longtext,
PRIMARY KEY (`id`),
UNIQUE KEY `name_UNIQUE` (`name`),
KEY `name` (`name`)
) ENGINE=InnoDB AUTO_INCREMENT=9159 DEFAULT CHARSET=utf8;
But everytime I try to run
INSERT INTO work_has_person (work_id, person_id, primary_contribution_id)
SELECT work_id, person_id, primary_contribution_id
FROM _work_has_person;
It says
Cannot add or update a child row: a foreign key constraint fails (`cdu93hfg93r`.
`work_has_person`, CONSTRAINT `fk_work_has_person_person1` FOREIGN KEY (`person_id`)
REFERENCES `person` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION)
I am pretty sure that the tables has the neccesary data, but, ¿is there a way to know which data fails? I have seen Mysql error 1452 - Cannot add or update a child row: a foreign key constraint fails: but don't understand exactly how to use it here.
A.
It is relatively easy to find out what data is causing the conflict: get all person_ids from _work_has_person that are not in the persons table. You can achieve this via an outer join and filtering for person.id is null in the where clause.
select * from `_work_has_person` whp
left join person p on whp.person_id=p.id
where p.id is null
You can actually remove such data from the results being inserted by including the reverse criterion into the select part of your insert query (an inner join):
INSERT INTO work_has_person (work_id, person_id, primary_contribution_id)
SELECT whp.work_id, whp.person_id, whp.primary_contribution_id
FROM _work_has_person whp
INNER join person p on whp.person_id=p.id

Cannot add foreign key constraint

I have created a database "webportal". and this is my "user" table script
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(255) DEFAULT NULL,
`password` varchar(255) DEFAULT NULL,
`firstName` varchar(255) DEFAULT NULL,
`lastName` varchar(255) DEFAULT NULL,
`dateRegistered` DATE DEFAULT NULL,
`skypeID` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
and this one is "catalog" table script.
DROP TABLE IF EXISTS `catalog`;
create table catalog(
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`link` VARCHAR(100) NOT NULL,
`comment` VARCHAR(100) NOT NULL,
`inserDate` DATE DEFAULT NULL,
`content` longblob NOT NULL,
PRIMARY KEY (`id`),
CONSTRAINT `fk_catalog` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
and when I try to execute the second script in the command line, I get this error...
ERROR 1215 (HY000): Cannot add foreign key constraint.
What is wrong with this code?
It seems you are using a old version of MySQL, you can add a INDEX clause to foreign key field to fix the problem:
DROP TABLE IF EXISTS `catalog`;
create table `catalog`(
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`link` VARCHAR(100) NOT NULL,
`comment` VARCHAR(100) NOT NULL,
`inserDate` DATE DEFAULT NULL,
`content` longblob NOT NULL,
PRIMARY KEY (`id`),
INDEX (`user_id`),
CONSTRAINT `fk_catalog` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Declare Foreign key in MySQL

I have these database
=== Invoices ===
id
status
description
=== Invoice Items ===
id
invoice_id (FK)
item_name
description
To make this table I have made this MySQL command
CREATE TABLE IF NOT EXISTS `nt_invoices` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`status` varchar(45) NOT NULL DEFAULT '',
`description` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=24 ;
CREATE TABLE IF NOT EXISTS `nt_invoice_items` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`invoice_id` int(11) NOT NULL,
`item_name` varchar(45) NOT NULL,
`description` text NOT NULL,
PRIMARY KEY (`id`),
KEY `invoice_id` (`invoice_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=12 ;
My problem is that I want to declare a foreign key in the invoice_items table and to make the invoice_id the foreign key of invoices table id. So how to write that command? Any help and suggestions will be highly appreciated.
MyISAM does not support foreign keys. You need to use InnoDB (which is a better choice in all aspects anyway). Then it's just like in any other SQL dialect:
`invoice_id` int(11) NOT NULL references nt_invoices(id),
P.S. Also, always use utf8 encoding everywhere. It will bite you in the ass if you don't.
You should have innodb engine type for using foreign keys.
CREATE TABLE IF NOT EXISTS `nt_invoice_items` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`invoice_id` int(11) NOT NULL references nt_invoices(id)
`item_name` varchar(45) NOT NULL,
`description` text NOT NULL,
PRIMARY KEY (`id`),
KEY `invoice_id` (`invoice_id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
OR if you want to use cascaded update delete:
CREATE TABLE IF NOT EXISTS `nt_invoice_items` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`invoice_id` int(11) NOT NULL,
`item_name` varchar(45) NOT NULL,
`description` text NOT NULL,
PRIMARY KEY (`id`),
KEY `invoice_id` (`invoice_id`),
FOREIGN KEY (invoice_id) REFERENCES nt_invoices(id)
ON DELETE CASCADE
ON UPDATE CASCADE,
) ENGINE=INNODB DEFAULT CHARSET=utf8;
You may also use ALTER command to declare FOREIGN KEY as follows:
Alter table table_name add foreign key(column_name)
references other_table_name(column);