如何优化(针对)多个表(成一个表)的删除查询?

时间:2019-02-10 18:12:59

标签: mysql codeigniter sql-delete

好吧,我目前正在从多个表中成功删除,其中三个查询选择存在category_id的行,除了一个,我使用一个子查询通过category_id获取post_id。怎样才能更有效,更全面地做到这一点?谢谢!

/**
 * delete category by id
 * @param $id
 * @return bool
 */
public function delete_category($id){

    $this->db->query("DELETE FROM categories WHERE categories.id = $id");
    $this->db->query("DELETE FROM comments
                      WHERE comments.post_id = ANY (SELECT post_id
                                                    FROM posts
                                                    WHERE category_id = $id)");
    $this->db->query("DELETE FROM posts
                      WHERE posts.category_id = $id
                      AND posts.category_id IS NOT NULL");
}

该代码可以正常工作,可以提供所需的结果,但是看起来有点毛病,我该如何优化它?

1 个答案:

答案 0 :(得分:0)

MySQL有一个multi-table DELETE syntax

从本质上讲,您将执行SELECT查询,该查询选择了要删除的行,并将SELECT * FROM更改为DELETE <table_name>, <table_name> FROM,其中<table_name>, <table_name>是要从中删除的表。

例如,如果您有以下DELETE查询:

DELETE FROM comments WHERE post_id IN (SELECT post_id FROM posts WHERE category_id = 1);
DELETE FROM posts WHERE category_id = 1;
DELETE FROM categories WHERE category_id = 1;

您可以将它们重写为SELECT,以选择要删除的所有行:

SELECT *
FROM categories
JOIN posts USING (category_id)
JOIN comments USING (post_id)
WHERE category_id = 1

然后,您可以将SELECT替换为多表DELETE

DELETE categories, posts, comments
FROM categories
JOIN posts USING (category_id)
JOIN comments USING (post_id)
WHERE category_id = 1