0

我正在尝试在 sqlite3 中创建一个计数器

c3 列是我的计数器

我需要的是一个触发器,如果​​ c1 和 c2 与更新语句不匹配,它将插入一个新行。

设置:

CREATE TABLE t1 (c1,c2,c3);
INSERT INTO t1 VALUES (1,1,1);

我的更新命令:

UPDATE t1 SET c3=(SELECT c3 FROM t1 WHERE c1=1 AND c2=1) + 1 WHERE c1=1 AND c2=1;

这是触发器,我得到了但它不起作用:

CREATE TRIGGER tr1 
BEFORE UPDATE ON t1 
  WHEN (SELECT COUNT(*) FROM t1 WHERE c1=NEW.c1 AND c2=NEW.c2) < 1 
    BEGIN 
      INSERT INTO t1 (c1,c2,c3) VALUES (NEW.c1, NEW.c2, 0); 
    END;

以下是我尝试过的一些绝望的事情:

CREATE TRIGGER tr1 BEFORE UPDATE ON t1 WHEN (SELECT COUNT(*) FROM t1 WHERE c1=1 AND c2=2) < 1 BEGIN INSERT INTO t1 (c1,c2,c3) VALUES (2, 2, 0); END;
CREATE TRIGGER tr2 BEFORE UPDATE ON t1 WHEN (SELECT COUNT(*) FROM t1 WHERE c1=NEW.c1 AND c2=NEW.c2) = 0 BEGIN INSERT INTO t1 VALUES (2, 2, 0); END;
CREATE TRIGGER tr3 AFTER UPDATE ON t1 WHEN (SELECT COUNT(*) FROM t1 WHERE c1=NEW.c1 AND c2=NEW.c2) = 0 BEGIN INSERT INTO t1 VALUES (2, 2, 0); END;
4

1 回答 1

0

让它与插入和 2 个触发器一起工作。

创建表 t1 (c1,c2,c3);

CREATE TRIGGER tr1 BEFORE INSERT ON t1 BEGIN SELECT RAISE(IGNORE) WHERE (SELECT COUNT(*) FROM t1 WHERE c1=NEW.c1 AND c2=NEW.c2) > 0;
END;
CREATE TRIGGER tr2 BEFORE INSERT ON t1 BEGIN UPDATE t1 SET c3=(SELECT c3 FROM t1 WHERE c1=NEW.c1 AND c2=NEW.c2) + 1 WHERE c1=new.c1 AND c2=new.c2;END;
COMMIT;

这将插入:

INSERT INTO t1 VALUES (1,1,1);

这将更新并增加计数器:

INSERT INTO t1 VALUES (1,1,1);

如果有人可以将这些触发器组合成一个,那就太好了。

于 2012-08-10T15:30:44.080 回答