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.
in the where statement, if you have more than one table reference, you should refer to TABLE.COLUMN,
eg : WHERE users.userid = '$userId'.
I recommend to do 1 sentence per table
In your WHERE, you have userId = '$userId'. Other people can correct me if I'm wrong, but I'm pretty sure that the userId would be ambiguous and this statement wouldn't run. @John Hartsocks answer should work though if that is indeed the case.
That is besides the point though. If you're worried about making sure a user is completely deleted, then you should be using foreign key constraints. You said when you delete a user, you want to make sure that all information pertaining to that user is deleted. If you add the FK constraint to every table that has a user id (besides the users table, in which case it would have the primary key constraint), it should not be possible for you to delete a user, without first making sure all other data referencing that user is deleted.
Yes.
http://dev.mysql.com/doc/refman/5.0/en/delete.html
精彩评论