从2个表中删除一对多关系

时间:2014-05-07 13:20:56

标签: mysql codeigniter codeigniter-2

我有3张桌子:文章:

id title content date

标记:

id  name

tags_in_news:

id  news_id  tag_id

news_id是文章表的外键,tag_id是标签表的外键...如何删除文章? 我试过但没有收到,我的代码:

$aid=(int)$this->uri->segment(3,0);
 $this->db->query("DELETE * FROM articles, tags_in_news WHERE articles.id = $aid AND tags_in_news.news_id = $aid ");

请帮帮我;)

2 个答案:

答案 0 :(得分:1)

您可以使用ON DELETE CASCADE选项在表上定义外键约束。

然后从父表中删除记录将从子表中删除记录。

DELETE articles a ,tags_in_news t FROM articles INNER JOIN tags_in_news  WHERE a.id = t.id AND a.id = $aid

参考:Mysql - delete from multiple tables with one query

答案 1 :(得分:1)

试试这个:

DELETE a, tn 
FROM articles a INNER JOIN 
     tags_in_news  tn
WHERE a.id=tn.news_id 
    AND a.id = $aid 
    AND tn.news_id = $aid 

另一种选择:

您可以使用ON DELETE CASCADE在表格上定义外键约束。

然后从父表中删除记录将从子表中删除记录。阅读更多here

信用:SO answer