zaho_account表是账户总表,zaho_tihuo_code是关联的子表。在zaho_account表中有一个字段:a_code_used,表示该账号下有多少条code记录。
DROP TRIGGER IF EXISTS `tihuo_code_insert`;
CREATE TRIGGER `tihuo_code_insert` AFTER INSERT ON `zaho_tihuo_code`
FOR EACH ROW BEGIN
UPDATE `zaho_account` SET a_code_used=a_code_used+1 WHERE a_id=NEW.account_id;
END//
-- 删除
DELIMITER //
DROP TRIGGER IF EXISTS `tihuo_code_delete`;
CREATE TRIGGER `tihuo_code_delete` AFTER DELETE ON `zaho_tihuo_code`
FOR EACH ROW BEGIN
UPDATE `zaho_account` SET a_code_used=a_code_used-1 WHERE a_id=OLD.account_id;
END//
-- 附赠一个把历史数据更新到a_code_used字段的SQL
UPDATE zaho_account a SET a_code_used=(select count(1) from zaho_tihuo_code where account_id=a.a_id)
关于MySQL触发器统计子表数量,本文就介绍这么多,希望对您有所帮助!