SQLite Trigger on one table for increment and decrement column other table

414 views Asked by At

So I have two tables, I want to have a column on one table increment or decrement as items on another table are added or deleted, the link is the FOREIGN key.

I have two triggers but I'm not sure if they would work. So I'd like some confirmation as to whether or not I'm barking up the right tree,if I'm going wrong or not an any fixes improvements?

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

There are 1 answers

5
CL. On BEST ANSWER

You are barking in the general direction of an okay tree.

But the outer WHEREs use the wrong ID: the agents table must use an agent ID, which NEW.id is not. And the MAX is not needed, and a subquery would need a SELECT.

UPDATE Agents
SET Office_Count = Office_Count + 1
WHERE Id = NEW.Agents_Id;