您可能在時間戳表中沒有任何記錄。觸發器確實按需要工作。請參見下面的輸出:
sqlite> CREATE TABLE devices(
...> id int PRIMARY KEY,
...> status text,
...> "timestamp" datetime,
...> FOREIGN KEY (timestamp) REFERENCES timestamps (controls)
...>);
sqlite> CREATE TABLE timestamps (
...> "database" datetime NOT NULL DEFAULT(CURRENT_TIMESTAMP),
...> controls datetime NOT NULL DEFAULT(CURRENT_TIMESTAMP)
...>);
sqlite> CREATE TRIGGER update_timestamps UPDATE OF status ON devices
...> BEGIN
...> UPDATE timestamps SET controls=datetime('now');
...> END;
sqlite>
將數據插入裝置和時間戳表
sqlite> insert into devices (status, "timestamp") values ('test',' 2011-05-05');
sqlite> select * from devices;
|test| 2011-05-05
sqlite>
sqlite> insert into timestamps values ('2010-01-01', '2010-01-01');
sqlite> select * from timestamps;
2010-01-01|2010-01-01
執行更新和通知觸發改變的時間戳數據;
sqlite>
sqlite> update devices set status = 'test1';
sqlite>
sqlite> select * from devices;
|test1| 2011-05-05
sqlite> select * from timestamps;
2010-01-01|2015-10-05 20:47:05
你可以插入,而不是在觸發做一個更新,像這樣的數據:
sqlite> create trigger insert_data_into_timestsamp update of status on devices
...> begin
...> insert into timestamps values (datetime('now'), datetime('now'));
...> end;
sqlite>
sqlite> select * from devices;
|test1| 2011-05-05
sqlite> select * from timestamps;
2010-01-01|2015-10-05 20:47:05
sqlite>
sqlite> drop trigger update_timestamps;
讓我們更新狀態3倍
sqlite> update devices set status = 'test';
sqlite> update devices set status = 'test1';
sqlite> update devices set status = 'test2';
注意,輸入了3條
sqlite> select * from timestamps;
2010-01-01|2015-10-05 20:47:05
2015-10-05 20:50:20|2015-10-05 20:50:20
2015-10-05 20:50:25|2015-10-05 20:50:25
2015-10-05 20:50:26|2015-10-05 20:50:26
但爲什麼沒有時間戳?我爲那些列指定了'DEFAULT CURRENT_TIMESTAMP' – rightaway717
好問題。 'DEFAULT CURRENT_TIMESTAMP'意味着當你執行'INSERT'時,如果沒有爲該列提供數據,將使用當前時間戳。 – zedfoxus
對於我來說,仍然不清楚,因爲你注意到'當前時間戳將被使用',所以我希望sqlite自己將當前時間插入到列中。這是不正確的? – rightaway717