SQLite在一个表上触发,用于递增和递减列其他表

时间:2016-12-28 16:13:33

标签: sqlite database-trigger

所以我有两个表,我希望在一个表的增量或减量上有一个列,因为添加或删除了另一个表上的项,链接是FOREIGN键。

我有两个触发器,但我不确定它们是否可行。 所以我想确认一下,如果我出错了或者没有任何改进措施,我是否会咆哮正确的树?

SQL =

CREATE TABLE IF NOT EXISTS Agents(
      Id INTEGER PRIMARY KEY,
      Name TEXT,
      Office_Count INT,
    );

    CREATE TABLE IF NOT EXISTS Branches(
      Id INTEGER PRIMARY KEY,
      Street_Address TEXT,
      City TEXT,
      Postcode TEXT,
      Agents_Id INTEGER,
      FOREIGN KEY(Agents_Id) REFERENCES Branches(Id)
    );

    CREATE TRIGGER Branches_Count_Increment AFTER INSERT ON Branches
    BEGIN
      UPDATE Agents SET
        Office_Count=(MAX(Office_Count)+ 1 FROM Branches Where Agents_Id=Agents.Id) WHERE Id=NEW.Id;
    END;

    CREATE TRIGGER Branches_Count_Decrement AFTER DELETE ON Branches
    BEGIN
      UPDATE Agents SET
        Office_Count=(MAX(Office_Count)- 1 FROM Branches Where Agents_Id=Agents.Id) WHERE Id=NEW.Id;
    END;

1 个答案:

答案 0 :(得分:1)

你正在向一棵好树的大方向狂吠。

但外部WHERE使用错误的ID:代理表必须使用代理ID,function init() { //...... // define the Node template myDiagram.nodeTemplate = $(go.Node, "Auto", new go.Binding("location", "loc", go.Point.parse).makeTwoWay(go.Point.stringify), // define the node's outer shape, which will surround the TextBlock $(go.Shape, "RoundedRectangle", { parameter1: 20, // the corner has a large radius fill: $(go.Brush, "Linear", { 0: "rgb(254, 201, 0)", 1: "rgb(254, 162, 0)" }), stroke: null, portId: "", // this Shape is the Node's port, not the whole Node fromLinkable: true, fromLinkableSelfNode: true, fromLinkableDuplicates: true, toLinkable: true, toLinkableSelfNode: true, toLinkableDuplicates: true, cursor: "pointer" }, new go.Binding("fill") // NEW ), $(go.TextBlock, { font: "bold 11pt helvetica, bold arial, sans-serif", editable: true // editing the text automatically updates the model data }, new go.Binding("text").makeTwoWay()) ); //...... } 不是。 并且不需要MAX,子查询需要SELECT。

NEW.id