我正在尝试在 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;