gpt4 book ai didi

php - 在子表更改时更新父表计数器

转载 作者:行者123 更新时间:2023-11-29 09:01:56 25 4
gpt4 key购买 nike

我的数据库中有三个表来跟踪我的网站类别

第一个是cat_parents

`parent_id` `parent_name`   `counter`
' 1 ' ' web design' ' 1 '

第二个是cat_subs

 `sub_id`  `parent_id` `sub_name`   `counter`
' 1 ' ' 1 ' ' php ' ' 1 '
' 2 ' ' 1 ' ' css ' ' 1 '
' 3 ' ' 1 ' ' xml ' ' 1 '

第三个是cat_articles

 `article_id`  `sub_id`  
' 2 ' ' 2 '
' 2 ' ' 3 '
' 3 ' ' 1 '

还有一个文章表,保存文章信息,如标题、文本和 ID它是这样的: 网页设计 (parent_cat) > php (sub_cat) > oop 编程 (article_name)

现在我希望能够根据我在 cat_articles 中删除或添加的每篇文章来增加和减少 cat_parentscat_subs 中的计数器表

现在我做了类似的事情(我刚刚写了这个,这不是我的原始代码,所以忽略语法错误)

public function add_article_to_category($article_id , $sub_id ){
$sql = " select `parent_id` from `cat_subs` where `id` = '$sub_id' " ;
$parent_id = $db->query($sql);

$sql = "update `cat_parents` set `counter` = counter + 1 where `parent_id` = $parent_id ";
$db->query($sql);


$sql = "update `cat_subs` set `counter` = counter + 1 where `sub_id` = $sub_id ";
$db->query($sql);

$sql = "INSERT INTO `cat_articles` ( `sub_id` , `article_id` ) values ('$sub_id' , '$article_id')";
$db->query($sql);
}

如你所见,我必须运行 3 个不同的查询,删除 cus 会变得最糟糕,我所要做的就是将文章 id 传递给函数

function delete_from_category($article_id){
$sql = "delete from `cat_articles` where `article_id` = '$article_id' " ;
}

我什至不需要这里的子ID(而且我不想将sub_id传递给这里的查询,因为每篇文章都可以在许多不同的子类别中,我首先必须获得所有这些,看起来很多工作 )

有没有更简单的方法?

我知道这是不对的,而且看起来很愚蠢!但类似这样的事情:

function delete_from_category($article_id){

$sql = "delete from `cat_articles` where `article_id` = '$article_id' and select

`sub_id`from this line and foreachDelete {

update `sub_cats` set `counter` = counter-1 where `sub_id` = $sub_idFromAboveLine and select `parent_id`

and( update `parent_cats` set `counter` = counter-1 where `parent_id` = $parent_idFromAboveLine ) ))" ;
}
<小时/>

好的,我要使用触发器了

这是我的代码,对吗?

 DELIMITER $$ 

CREATE TRIGGER decrease_counter AFTER DELETE ON cat_article
FOR EACH ROW BEGIN
UPDATE cat_subs SET counter= counter-1 WHERE cat_subs.sub_id = cat_article.sub_id ;
END
$$ DELIMITER ;

我应该为 cat_parents 编写单独的触发器还是可以使用这个?像:

CREATE TRIGGER decrease_counter AFTER DELETE ON cat_article
FOR EACH ROW BEGIN
UPDATE cat_subs SET counter= counter-1 WHERE cat_subs.sub_id = cat_article.sub_id ;
FOR EACH ROW BEGIN
UPDATE cat_parents SET counter= counter-1 WHERE cat_subs.parent_id=cat_parents.parent_id ;
END
END
$$ DELIMITER ;

最佳答案

首先,您应该使用事务来执行此操作。您有 3 个以上的查询,每个查询都相互依赖。如果其中一个失败了,那么所有的人都应该失败。现在,如果您的“插入”失败但更新成功,您最终会得到不正确的文章计数。

除此之外,您还可以使用trigger来实现此功能。 。它将捕获 cat_articles 表上的任何插入/删除,并自动对 cat_parents 和 cat_subs 运行适当的更新。即使仍会执行 3 个查询,您的代码只会发出一个“插入”或“删除”查询 - DBMS 将在后台为您处理其余的事情。

关于php - 在子表更改时更新父表计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8360656/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com