简体   繁体   English

如何删除数据库中MySQL表中的相关数据?

[英]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. 我确信这是一个非常基本的问题,但是我茫然不知所措,最近开始使用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. 我已经修改,创建了数据库,用户,表,向表中添加和修改了条目,但是现在我认为我需要在此处使用Join,但是我不确定。

In the same db I have two tables. 在同一个数据库中,我有两个表。 The tasks table has two columns of interest user and keyid. 任务表有两列感兴趣的用户和密钥ID。 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. 现在,它们之间的关联方式是,任务表中的keyid值是活动表中task列中的值。

My question is how do I write the DROP or DROP + JOIN query to do this? 我的问题是如何编写DROP或DROP + JOIN查询来做到这一点?

You could do it in 2 separate queries? 您可以在2个单独的查询中执行此操作?

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: 您可以像这样使用JOIN

 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. 但是最好在设计表时使用ON DELETE CASCADE ,以便必须从母表中删除,并且子表的所有相关记录也将被自动删除。

See example here . 在这里查看示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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