我正在尝试在sqlite3中创建一个计数器
列c3是我的计数器
如果c1和c2与update语句不匹配,我需要的是一个插入新行的触发器。
设置:
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;
答案 0 :(得分:0)
使用insert和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);
如果有人可以将这些触发器组合成一个很棒的触发器。