在PHP中一次删除3个表中的行

时间:2012-05-03 19:46:48

标签: php mysql sql mysqli prepared-statement

我的表结构看起来像那样

enter image description here

这是Sql语句

            $stmt = $this->db->prepare("DELETE FROM chapters WHERE (subject_id=? AND id = ?)") or die($this->db->error());
            $stmt->bind_param("ii", $subject_id, $node);
            $stmt->execute();
            $stmt = $this->db->prepare("DELETE FROM sections WHERE (subject_id=? AND chapter_id=? )") or die($this->db->error());
            $stmt->bind_param("ii", $subject_id, $node);
            $stmt->execute();
            $stmt = $this->db->prepare("DELETE FROM paragraphs WHERE (subject_id=? AND chapter_id=?)") or die($this->db->error());
            $stmt->bind_param("ii", $subject_id, $node);
            $stmt->execute();

所以我想做的是,将{3}这3个语句合并为一个并优化服务器负载。

详细

例如,如果我想从merge表中删除id = 1的行,那么还要从另外2个表中删除chapterssections 2个参数:{{ 1}}和paragraphs(当然,如果有行包含这些参数。我的意思是必须有连接以防止任何错误)。

问题是......

这可能吗?我无法弄清楚,sql语句必须如何。有什么建议吗?

2 个答案:

答案 0 :(得分:6)

如果您使用ON DELETE CASCADE设置了外键约束,则只需删除父行。然后,MySQL将自动删除子行。

答案 1 :(得分:4)

我没有尝试过,但您可以尝试多表删除:

http://dev.mysql.com/doc/refman/5.6/en/delete.html#id933512

    DELETE chapters, sections, paragraphs
    FROM      chapters
    LEFT JOIN sections   ON   sections.subject_id = $subject_id AND   sections.chapter_id = $node
    LEFT JOIN paragraphs ON paragraphs.subject_id = $subject_id AND paragraphs.chapter_id = $node
    WHERE                     chapters.subject_id = $subject_id AND chapters.id           = $node

我不确定使用左连接是否比使用3个单独的删除更快。