Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this a valid MySQL query?

Tags:

sql

mysql

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

like image 228
Ali Avatar asked Jan 24 '26 08:01

Ali


2 Answers

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]
like image 80
John Hartsock Avatar answered Jan 27 '26 00:01

John Hartsock


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.

like image 40
Quassnoi Avatar answered Jan 26 '26 23:01

Quassnoi