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

好久不见. 提交于 2019-12-25 07:22:35

问题


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. 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?


回答1:


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).




回答2:


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

You can go through the explanation present in delete on cascade




回答3:


if you are using php you can try the following

//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...

hope this helps



来源:https://stackoverflow.com/questions/18381529/how-do-i-delete-row-with-primary-key-using-foreign-key-from-other-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!