我需要使用外键从多个表中删除多行

时间:2014-06-17 13:43:09

标签: mysql sql-delete cascade

我有三个不同的表格,例如tbl1tbl2tbl3。我需要从三个表中的每个表中删除行。唯一的问题是,每个表之间存在外键约束。如果我从tbl1删除了一行,则删除级联并删除引用tbl2中已删除行的tbl3tbl1中的所有行。如何只删除特定的行?

3 个答案:

答案 0 :(得分:0)

这是一种方法:

 DELETE FROM tbl3 WHERE tbl3.tbl1_id = 'foo';
 DELETE FROM tbl2 WHERE tbl2.tbl1_id = 'foo';
 DELETE FROM tbl1 WHERE tbl1.tbl1_id = 'foo';

答案 1 :(得分:0)

有两种方式

  1. 您应设置外部约束 ON DELETE CASCADE 并仅从第一个表中删除
  2. 您可以使用3删除查询
  3. 进行级联手动

答案 2 :(得分:-1)

如果($ _ REQUEST [ '动作'] == '删除')         {

        $id=$_REQUEST['site_id'];
        $qry_arry=mysql_query("Select site_name from site where site_id=$id and client_id='".$client_id."'");
        $site_qry=mysql_fetch_array($qry_arry);
        $site_nm=$site_qry['site_name'];
        $del_server=mysql_query("DELETE FROM `server` where site_name='".$site_nm."' and client_id='".$client_id."'");
        $del_work=mysql_query("DELETE FROM `workstation` where site_name='".$site_nm."' and client_id='".$client_id."'");
        $qry=mysql_query("DELETE FROM `site` where  site_id=$id and client_id='".$client_id."'");
        if(isset($del_server) && isset($del_work) && isset($qry))
        {
        $msg='<div style="width:450px; -webkit-border-radius:5px;   -moz-border-radius:5px; border-radius:5px; font-family:Arial, Helvetica, sans-serif; font-size:14px; color:#000000; text-decoration:none; border:solid 1px #999999; margin:5px; padding:5px; background:#BFFFBF;">Deleted successfully </div>';
                    echo "<script>window.location = 'https://portal.itimpulse.in/home-3' </script>";
            }       
                    exit(0);
    }