04/01/2011

MySQL: DELETE across multiple tables using JOIN.

Ever had a situation where you’ve wanted to say delete rows from lots of tables in your database that can all be associated with some form of join?


Well, after a few minutes of playing around, I’ve found a nice way to do this in just 1 query:
DELETE u, up, upc, ut, utp
FROM users AS u
LEFT JOIN users_photos AS up ON up.user_id = u.id
LEFT JOIN users_photos_comments AS upc ON upc.photo_id = up.id
LEFT JOIN users_topics AS ut ON ut.user_id = u.id
LEFT JOIN users_topic_posts AS utp ON utp.topic_id = ut.id
WHERE u.id = 12

The code is pretty straight forward, and simple to use.


taken from
http://www.haughin.com/2007/11/01/mysql-delete-across-multiple-tables-using-join/

No comments:

Post a Comment