我有下一个关系(我只留下相关的字段):
CREATE TABLE "operations" (
"id" serial NOT NULL,
"opdate" timestamp DEFAULT current_timestamp NOT NULL,
);
CREATE TABLE "prows" (
"id" serial NOT NULL,
"operation_id" integer NOT NULL,
);
ALTER TABLE "prows" ADD CONSTRAINT "prows_fk_operation_id" FOREIGN KEY ("operation_id")
REFERENCES "operations" ("id") ON DELETE CASCADE ON UPDATE RESTRICT;
CREATE TRIGGER "prow_bd_changesaldo" before delete
ON "prows" FOR EACH row EXECUTE PROCEDURE make_prow()
;
CREATE FUNCTION "make_prow" ()
RETURNS TRIGGER
LANGUAGE plpgsql
AS $$
DECLARE _count INT;
BEGIN
SELECT count(*) /* OP.OpDate */
FROM Operations OP
WHERE OP.ID = OLD.Operation_ID
INTO _count;
RAISE NOTICE 'COUNT: %', _count;
...
IF TG_OP = 'DELETE' THEN RETURN OLD; ELSE RETURN NULL; END IF;/**/
END;/**/
$$
我知道count
为零:
delete from operations ;
NOTICE: COUNT: 0
CONTEXT: PL/pgSQL function make_prow() line 1 at RAISE
SQL statement "DELETE FROM ONLY "public"."prows" WHERE $1 OPERATOR(pg_catalog.=) "operation_id""
...
当引用的行消失时,相关的行仍然存在。这对我来说似乎很不一致,打破了诚信。
有没有办法从Operations.OpDate
触发器中获取make_prow
值?
答案 0 :(得分:1)
DELETE
仅在prows
中的行被删除后才operations
级联,这并不奇怪。
要解决此问题,您可以将ON DELETE CASCADE
更改为ON DELETE NO ACTION
并在BEFORE
上定义operations
触发器,删除prows
之前删除operations
中的行。这样,prows
中的行将在operations
中的行消失之前被调用。