I trying to come up with the best solution to delete rows from child table in my sql.
e.g I have two tables, one is called users the other is called users_information. The second table, users_information uses a foreign key called user_id which is actually the "id" in "users" table.
I want to use the cascade delete option, whenever I delete a row from "users" table (by using "id" ofc) I'd like to remove the same row inside users_information where id = user_id.
I'm having a hard time figuring it out, tried looking and found How do I use on delete cascade in mysql?
But that isn't explained well, I'm sure it is the solution I aim for nevertheless.
Here's my tables structure, If you see anything I might be doing wrong / not the best way, tell me.
CREATE TABLE `users_information` (
`id` int(20) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`first_name` varchar(15) NOT NULL,
`last_name` varchar(15) NOT NULL,
`country` varchar(30) NOT NULL,
`profession` varchar(40) NOT NULL,
`gender` varchar(6) NOT NULL,
`birthday` datetime NOT NULL,
`city` varchar(50) NOT NULL,
PRIMARY KEY (`id`),
KEY `user_id` (`user_id`)
CONSTRAINT `myForeignKey` FOREIGN KEY (`user_id`)
REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `users` (
`id` int(20) NOT NULL AUTO_INCREMENT,
`password` varchar(82) NOT NULL,
`email` varchar(60) NOT NULL,
`created` date NOT NULL,
`user_type` int(2) NOT NULL,
`active` smallint(2) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
I forgot to mention: the code for "users_information" produces the following error:
* #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'CONSTRAINT
myForeignKey
FOREIGN KEY (user_id
) REFERENCESusers
(id
) O' at line 13