users
和products
,它们之间的关联是User has many products
。我想在用户表中存储产品数量,并且每次插入或删除时都应该更新该数量。因此,我已经在数据库中编写了存储过程,并使用触发器来触发它。问题在于,当我一次插入数千个产品时,它会执行每行插入的触发器per row insertion
,这需要太多时间。 CREATE FUNCTION update_product_count()
RETURNS trigger AS $$
BEGIN
IF TG_OP = 'DELETE' THEN
UPDATE users SET products_count = products_count - 1 WHERE id = OLD.user_id;
END IF;
IF TG_OP = 'INSERT' THEN
UPDATE users SET products_count = products_count + 1 WHERE id = NEW.user_id;
END IF;
RETURN NULL;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER update_user_products_count
AFTER INSERT OR UPDATE OR DELETE ON products
FOR EACH ROW EXECUTE PROCEDURE update_product_count();
更新
i have added:
SET CONSTRAINTS update_promotion_products_count DEFERRED;
but seems like it is not making any progress because right now it is taking 6100ms which is somewhat similar to before.Tried
DEFERRABLE INITIALLY DEFERRED
but it is still not working. I thinkFOR EACH ROW
is the actual issue. But when i tried it withFOR EACH STATEMENT
it throws statement invalid error.Rewrote the above procedure like this:
CREATE FUNCTION update_product_count() RETURNS trigger AS $$ BEGIN IF TG_OP = 'DELETE' OR TG_OP = 'INSERT' THEN UPDATE users SET products_count = (SELECT COUNT(1) FROM products WHERE products.user_id = users.id); END IF; RETURN NULL; END; $$ LANGUAGE plpgsql; CREATE TRIGGER update_user_products_count AFTER INSERT OR UPDATE OR DELETE ON products FOR EACH STATEMENT EXECUTE PROCEDURE update_product_count();
然而问题在于,当你有1000个用户,每个用户有10000个产品时,即使只向数据库插入一个产品,你也需要重新计算每个用户的数量。
我正在使用PostgreSQL 9.6。