CREATE TABLE db3_parts ( name text NOT NULL, date timestamp, comment text, PRIMARY KEY (name, date) );
CREATE TABLE db3_parts_recent AS SELECT * FROM db3_parts; -- db3_parts 、ネニア、ク
CREATE FUNCTION db3_parts_tri() RETURNS TRIGGER AS ' DECLARE BEGIN DELETE FROM db3_parts_recent WHERE name=NEW.name; INSERT INTO db3_parts_recent SELECT * FROM db3_parts WHERE name=NEW.name and date IN (SELECT max(date) FROM db3_parts WHERE name=NEW.name); RETURN NEW; END; ' LANGUAGE 'PLpgSQL'; CREATE FUNCTION db3_parts_delete_tri() RETURNS TRIGGER AS ' DECLARE BEGIN DELETE FROM db3_parts_recent WHERE name=OLD.name; INSERT INTO db3_parts_recent SELECT * FROM db3_parts WHERE name=OLD.name and date IN (SELECT max(date) FROM db3_parts WHERE name=OLD.name); RETURN OLD; END; ' LANGUAGE 'PLpgSQL';
CREATE TRIGGER db3_parts_change AFTER insert OR update
ON db3_parts FOR EACH ROW execute procedure db3_parts_tri();
CREATE TRIGGER db3_parts_delete AFTER delete
ON db3_parts FOR EACH ROW execute procedure db3_parts_delete_tri();
INSERT INTO db3_parts VALUES ('L6203 Motor Driver', '2006-01-25', 'ソキオャコ鋿ョ'); INSERT INTO db3_parts VALUES ('L6203 Motor Driver', '2006-01-26', 'クホセ); INSERT INTO db3_parts VALUES ('12V Power Supply', '2006-01-26', 'ソキオャコ鋿ョ'); INSERT INTO db3_parts VALUES ('L6203 Motor Driver', '2006-01-27', 'ヌムエ);
で、以上のデータを追加したときの各テーブルの結果については、こんな感じです。
db_practice=# select * from db3_parts_recent ; name | date | comment --------------------+---------------------+---------- 12V Power Supply | 2006-01-26 00:00:00 | 新規作成 L6203 Motor Driver | 2006-01-27 00:00:00 | 廃棄 (2 行) db_practice=# select * from db3_parts; name | date | comment --------------------+---------------------+---------- L6203 Motor Driver | 2006-01-25 00:00:00 | 新規作成 L6203 Motor Driver | 2006-01-26 00:00:00 | 故障 12V Power Supply | 2006-01-26 00:00:00 | 新規作成 L6203 Motor Driver | 2006-01-27 00:00:00 | 廃棄 (4 行) db_practice=#
以上。
なんか、説明してない気がしますけど...。