如何从PostgreSQL内的其他表中收集信息触发

时间:2015-08-07 03:09:05

标签: sql postgresql triggers

我有一个引用Filing Cabinet表的Drawer表。我想为它们的行自动生成标签(参见下面的MWE)。例如,第三行和第一个房间的文件柜将是 03:01 ,其第二列的抽屉,第一列将是 03:01:02:01 即可。我知道如何在接口级别(Python / PHP)执行此操作,但希望在数据库级别实现此目的。这可能是可取的吗?

CREATE TABLE Drawer(
   id SERIAL PRIMARY KEY,
   drawerCol INT,
   drawerRow INT,
   label Varchar(256)
);

CREATE TABLE FilingCabinet(
   id SERIAL PRIMARY KEY,
   room INT,
   floor INT,
   label VARCHAR (256),
   drawerId INT REFERENCES Drawer (id) UNIQUE --Ensures two rooms don't share a drawer
);

CREATE OR REPLACE FUNCTION f_update_labels() RETURNS TRIGGER AS $update_labels$
BEGIN
   --set FilingCabinet label to be floor:room
   --set Drawer label to be floor:room:drawerRow:drawerCol
   if FALSE THEN
      NEW.id := OLD.id; --Avoid psql throwing an error
   END IF;
   RETURN NEW;
END; $update_labels$ LANGUAGE plpgsql;

CREATE TRIGGER update_labels
   BEFORE INSERT OR UPDATE ON FilingCabinet
   FOR EACH ROW
   EXECUTE PROCEDURE f_update_labels ();

INSERT INTO Drawer (drawerCol,drawerRow) VALUES (1,1);
INSERT INTO Drawer (drawerCol,drawerRow) VALUES (1,2);
INSERT INTO Drawer (drawerCol,drawerRow) VALUES (1,3);
INSERT INTO Drawer (drawerCol,drawerRow) VALUES (1,1);
INSERT INTO Drawer (drawerCol,drawerRow) VALUES (1,2);
INSERT INTO Drawer (drawerCol,drawerRow) VALUES (1,3);

INSERT INTO FilingCabinet (room,floor,drawerId) VALUES (1,1,1);
INSERT INTO FilingCabinet (room,floor,drawerId) VALUES (1,1,2);
INSERT INTO FilingCabinet (room,floor,drawerId) VALUES (1,1,3);
INSERT INTO FilingCabinet (room,floor,drawerId) VALUES (1,2,4);
INSERT INTO FilingCabinet (room,floor,drawerId) VALUES (1,2,5);
INSERT INTO FilingCabinet (room,floor,drawerId) VALUES (1,2,6);

1 个答案:

答案 0 :(得分:1)

void TimeSpent(std::function<void()> func)
{
  const int ONE_MIL = 10000;
  long times = ONE_MIL;
  std::chrono::steady_clock::time_point start = std::chrono::steady_clock::now();
  while (times > 0)
  {
    func();
    --times;
  }
  std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now();
  cout << "time elapsed : " << std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count() << endl;
}