简体   繁体   English

如何使用其他表中的外键删除具有主键的行?

[英]How do I delete row with primary key using foreign key from other table?

I have a table called 'agenda' //translation: dairy 我有一张叫“议程”的表//翻译:乳制品

with the following rows: 具有以下行:

idagenda // primary key
title
waar
organisatie
...
etc.
...

I also have a table for the date of an diary item/event called agendadatum 我还有一张表,用于记录日记项目/事件的日期,称为议程

with the following rows: 具有以下行:

id // primary key
idagenda // id from other table
van //from
tot // till
datum // date

When the field 'tot' is the date from Today it will delete the rows from the database, but the rows in the 'agenda' table remain untouched. 当“ tot”字段是“今天”的日期时,它将删除数据库中的行,但“议程”表中的行保持不变。 They're not deleted, because I did not call them. 他们没有被删除,因为我没有给他们打电话。

My delete query looks like this: 我的删除查询如下所示:

DELETE FROM agendadatum WHERE tot < NOW(); 

How can I also delete the rows from 'agenda' table, that have the same id then the foreign key in agendadatum? 如何从“议程”表中删除具有相同ID的行,然后删除议程表中的外键?

In your create table you need to mention the Foreign Key Constraint like 在创建表中,您需要提及外键约束,例如

FOREIGN KEY (product_id) REFERENCES products (id)
       ON DELETE CASCADE
       ON UPDATE CASCADE,

and after that If you run the delete query, automatically the rows will be deleted, which is referencing the ids of the table 之后,如果您运行delete查询,则将自动删除引用表ID的行。

You can go through the explanation present in delete on cascade 您可以查看级联删除中的说明

if you are using php you can try the following 如果您使用的是php,则可以尝试以下操作

//get all agentadatum data with date now and before
$select_agendadatum = mysql_query("SELECT * FROM agendadatum WHERE tot <= NOW()") or die (mysql_error());
//loop through rows
while($row_agendadatum = mysql_fetch_assoc($select_agendadatum))
{
     //delete agendadatum row
     $delete_agendadatum = mysql_query("DELETE FROM agendadatum WHERE id = '".$row_agendadatum['id']."'") or die (mysql_error());
    //delete agenda row
    $delete_agenda= mysql_query("DELETE FROM agenda WHERE idagenda = '".$row_agendadatum['idagenda']."'") or die (mysql_error());
}

if your logic accepts more than one agendadatum per agenta you can simply count if there is more than 1 agendadatum in a specific agenta before deleting the agenta... 如果您的逻辑上每个agenta接受一个以上的议事日程,则可以在删除该agenta之前简单地计算一个特定agenta中是否有超过1个议事日程...

hope this helps 希望这可以帮助

You can delete from multiple tables in one query: 您可以在一个查询中从多个表中删除:

DELETE agenda.*, agendadatum.*
FROM agenda
JOIN agendadatum USING (idagenda)
WHERE tot < NOW();

This will delete rows from both agenda and agendadatum, and only those rows matching the conditions (same rows as returned by the query if you replaced DELETE with SELECT ). 这将从议程和议程基准中删除所有行,并且仅删除那些与条件匹配的行(如果将DELETE替换为SELECT则返回与查询相同的行)。

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

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