我的表结构看起来像那样
这是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个表中删除chapters
,sections
2个参数:{{ 1}}和paragraphs
(当然,如果有行包含这些参数。我的意思是必须有连接以防止任何错误)。
这可能吗?我无法弄清楚,sql语句必须如何。有什么建议吗?
答案 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个单独的删除更快。