Jump to content
Larry Ullman's Book Forums

How To Delete A User From One Table And Its Content From Another Table?


Recommended Posts

Hello,

 

I have users table and comments table.

How can I delete a user from the users' table and at the same time get anything associated with this users in the comments table deleted automatically ?

Link to comment
Share on other sites

I would firstly ask are you sure you want to delete all the info. Would you prefer to make the user inactive, therefore keeping their details incase they come back? I'm not saying your wrong at all, just confirming your sure you want to delete all the user and comment details

  • Upvote 1
Link to comment
Share on other sites

I would firstly ask are you sure you want to delete all the info. Would you prefer to make the user inactive, therefore keeping their details incase they come back? I'm not saying your wrong at all, just confirming your sure you want to delete all the user and comment details

Would you please tell me how to do it in both cases?

I am not working on a project. I only create tables and perform tasks on the form learning purposes.

Link to comment
Share on other sites

By looking at the manual, try something like this. (You will of course need to modify table names, etc)

 

NB: Remember to backup table if you want to keep the data safe!

DELETE users, comments

FROM users

INNER JOIN comments ON (users.id = comments.user_id)

WHERE users.id = {$user_id}

  • Upvote 1
Link to comment
Share on other sites

If you're using InnoDB tables and have foreign key constraints implemented, then deleting from the parent table (e.g., users) will automatically delete from the child table (e.g., comments).

  • Upvote 1
Link to comment
Share on other sites

 Share

×
×
  • Create New...