Search code examples
mysqlsql-delete

Delete from 2 tables


I have 2 tables in my DB

users...

ID    Username    Randomkey
1     Dionne      938493
2     Liam        902303
3     James       232039
4     Sarah       320923

interests...

ID    User_ID    Interest
1     3          Army
2     3          Boxing
3     3          Tennis
4     4          Make Up

In my interests table, 'User_ID' is equal to 'ID' from my users table.

I want to write a query that when triggered, deletes the row from my 'users' table and at the same time deletes all data relating to the user from the interests table.

I'm unsure how to do this and I've had no luck with Google.

If anybody could give me some advice or at least point me where to find this information it would be a great help.

In my head I'm thinking it would be something along the lines of:

DELETE FROM users, interests WHERE ID = '$userID' AND User_ID = '$userID'

Solution

  • DELETE users, interests 
    FROM users 
    LEFT JOIN interests ON users.ID = interests.User_ID
    WHERE users.ID = <id>;
    

    Of course, if the interests table was InnoDB & had a foreign key constraint to users with an ON DELETE CASCADE this would be done automatically when a user gets deleted.