Reputation: 69
How can I add on delete cascade to this table creation script? id_fk comes from mytable table.
CREATE TABLE IF NOT EXISTS `ip` (
`ip_id` int(11) NOT NULL AUTO_INCREMENT,
`id_fk` int(11) DEFAULT NULL,
`ip_add` varchar(40) DEFAULT NULL,
PRIMARY KEY (`ip_id`),
KEY `id_fk` (`id_fk`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;
Upvotes: 1
Views: 896
Reputation: 16107
Add a foreign key constraint and specify what to do and when.
ALTER TABLE ip
ADD CONSTRAINT constraint_name
FOREIGN KEY index_name(id_fk)
REFERENCES other_table(other_column_name)
ON DELETE CASCADE
ON UPDATE CASCADE;
You can include the constraint directly in the table definition:
FOREIGN KEY index_name(id_fk)
REFERENCES other_table(other_column_name)
ON DELETE CASCADE
ON UPDATE CASCADE;
Upvotes: 0
Reputation: 555
Try this:
ALTER TABLE `ip`
ADD CONSTRAINT `FK_mytable` FOREIGN KEY (`id_fk`) REFERENCES `mytable` (`id`)
ON DELETE CASCADE ON UPDATE CASCADE;
Hope this helps!
Upvotes: 2