我想要创建的sqlite3触发器可能是也可能不是sql。涉及五个表:
Members Groups GroupMembers Accounts
mId |name| accId gId | name | accId gId | mId accId | balance
Orders
oId | accId | ammount
当有人删除某个群组时,我想为每个群组成员订阅一个群组余额的平均值。所以它应该做这样的事情:
CREATE NEW TRIGGER triggername
BEFORE DELETE ON Groups
WHEN ((SELECT balance FROM Accounts WHERE accId=OLD.accId) = 0)
FOR EACH ROW IN
(SELECT accId
FROM GroupMembers JOIN Members ON GroupMembers.mId = Members.mId
WHERE GroupMembers.gId = OLD.gId)
BEGIN
INSERT INTO Orders(accId,ammount) VALUES(accId,
(SELECT balance FROM Accounts WHERE accId = OLD.accId)
/
(SELECT SUM(mId) FROM GroupMembers WHERE gId = OLD.gId)
);
END
问题是:是否可以在触发器适用的表之外的任何其他表中创建FOR EACH ROW?是否可以在FOR EACH语句之前加上WHEN语句?
答案 0 :(得分:0)
作为documented,没有FOR EACH ROW IN ...
子句这样的东西。
然而,INSERT
声明can use a SELECT
statement as the source of the data to be inserted。
编写一个SELECT
语句,为每个组成员返回一行:
CREATE TRIGGER triggername
AFTER DELETE ON Groups
FOR EACH ROW
BEGIN
INSERT INTO Orders(accId, amount)
SELECT accId,
(SELECT balance
FROM Accounts
WHERE accId = OLD.accId) /
(SELECT COUNT(*)
FROM GroupMembers
WHERE gId = OLD.gId)
FROM Members
WHERE mId IN (SELECT mId
FROM GroupMembers
WHERE gId = OLD.gId);
END;
(我放弃了balance = 0
过滤器。)