我有这两个表Review&Listing
| listing_id | review_id | comment |
|------------|----------------------------|--------------------|
| 5629709 | 123 | Beautiful |
| 4156372 | 231 | Wonderful |
| 4156372 | 432 | Very Good |
| 4156372 | 649 | Excellent |
| listing_id | number_of_reviews |
|------------|----------------------------|
| 5629709 | 1 |
| 4156372 | 2 |
是否有一种创建触发功能的方法,当Review表具有更新(插入或删除)时,Listing表中的number_of_reviews列也会更新(+1或-1)?
答案 0 :(得分:0)
可以从其他值计算得出的材料化值会产生严重的不一致风险。尽可能避免这种情况。
在您的情况下,将number_of_reviews
列中的listing
放下,然后创建一个用于计算该列编号的视图。
CREATE VIEW listing_with_number_of_reviews
AS
SELECT l.listing_id,
count(r.review_id) number_of_reviews
FROM listing l
LEFT JOIN review r
ON r.listing_id = l.listing_id
GROUP BY l.listing_id;
答案 1 :(得分:0)
CREATE OR REPLACE FUNCTION function_number_of_reviews() RETURNS TRIGGER AS
$BODY$
BEGIN
if TG_OP='INSERT' then
Update public."Listing" set number_of_reviews = number_of_reviews + 1 where id = new.listing_id;
end if;
if TG_OP='DELETE' then
Update public."Listing" set number_of_reviews = number_of_reviews - 1 where id = old.listing_id;
end if;
RETURN new;
END;
$BODY$
language plpgsql;
CREATE TRIGGER trig_number_of_reviews
AFTER INSERT OR DELETE ON public."Review"
FOR EACH ROW
EXECUTE PROCEDURE function_number_of_reviews();
这是明智的方式