简体   繁体   中英

How do delete related data in MySQL tables in a database?

I'm sure that this is a very basic question but, I at a loss and recently starting with MySQL. I have modified, created databases, users, tables, added and modified entries to the table but now I think I need to use a Join here, but I'm not sure.

In the same db I have two tables. The tasks table has two columns of interest user and keyid. While the activities table has one column of interest which is task. What I need to do is delete all tasks in the table tasks for a certain user. However, this also means I need to delete all activities for those tasks. Now the way these are related, is that the keyid value in the tasks table is the value in the task column in the activities table.

My question is how do I write the DROP or DROP + JOIN query to do this?

You could do it in 2 separate queries?

DELETE FROM activities WHERE task IN 
     ( SELECT keyid FROM tasks WHERE user  = 'CertainUser') ;
DELETE FROM tasks WHERE user = 'CertainUser' ;

You could use JOIN on this one like:

 DELETE Tasks, Activities
 FROM Tasks INNER JOIN Activities
 ON Tasks.KeyID = Activities.Task
 WHERE Tasks.User = 'User Name Here'

But it would have been better if you use ON DELETE CASCADE when you designed the table so that you will have to delete from the mother table and all the related records of the child table would also be deleted automatically.

See example here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM