While working in a php and mysql project I have faced to remove child table's rows while deleting it's parent table's items and here is my solution for such kind of functionality:
Suppose that I have two tables named user_roles and users:
CREATE TABLE `user_roles` (
`id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
`name` varchar(64) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
`name` varchar(128) NOT NULL,
`address` varchar(255) DEFAULT NULL,
`email` varchar(128) NOT NULL,
`password` varchar(64) NOT NULL,
`role_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
and below is the code to obtain such above functionality:
ALTER TABLE users
ADD CONSTRAINT FK_RoleUser
FOREIGN KEY (role_id) REFERENCES user_roles(id)
ON DELETE CASCADE
so now if you delete any row of table user_roles then all the users related to that role id will be deleted automatically.
Suppose that I have two tables named user_roles and users:
CREATE TABLE `user_roles` (
`id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
`name` varchar(64) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
`name` varchar(128) NOT NULL,
`address` varchar(255) DEFAULT NULL,
`email` varchar(128) NOT NULL,
`password` varchar(64) NOT NULL,
`role_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
and below is the code to obtain such above functionality:
ALTER TABLE users
ADD CONSTRAINT FK_RoleUser
FOREIGN KEY (role_id) REFERENCES user_roles(id)
ON DELETE CASCADE
so now if you delete any row of table user_roles then all the users related to that role id will be deleted automatically.
Is it possible to make this functional without ALTER TABLE query?
ReplyDeleteI mean, with CREATE TABLE command, will it be able to do that relation between two tables?