I've got 4 tables: users, messages, files, notes. I want to make a query which will delete all of a users' stuff if he's deleted. Will the following work:
DELETE FROM users, messages, files, notes WHERE userId = '$userId'
All 4 tables have got the column userId
You can split the statements in to four separate statements, in order to delete the rows associated with the userid.
DELETE FROM users WHERE userId = '$userId'
DELETE FROM messages WHERE userId = '$userId'
DELETE FROM files WHERE userId = '$userId'
DELETE FROM notes WHERE userId = '$userId'
The other alternative would be to cascade the deletes across the foreign keys.
When you create a foreign key you can choose what you want to do to the child records on the deletion of a parent record. This is denoted below by specifying the ON Delete in the creation of the foreign key. Here is some reference http://dev.mysql.com/doc/refman/5.5/en/innodb-foreign-key-constraints.html
[CONSTRAINT [symbol]] FOREIGN KEY
[index_name] (index_col_name, ...)
REFERENCES tbl_name (index_col_name,...)
[ON DELETE reference_option]
[ON UPDATE reference_option]
DELETE u, m, f, p
FROM users u
LEFT JOIN
messages m
ON m.user_id = u.id
LEFT JOIN
files f
ON f.user_id = u.id
LEFT JOIN
posts p
ON p.user_id = u.id
WHERE u.id = 1
This assumes that the record with id = 1 exists in users, otherwise nothing will be deleted.
Note, however, that this is not very efficient and four separate deletes will work better.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With