7

I need to keep track of the time a row was inserted into the database, and the time it was last modified.

I tried to create two separate columns, and use CURRENT_TIMESTAMP:

create table def (
  id int, 
  creation timestamp 
    default CURRENT_TIMESTAMP, 
  modification timestamp 
    on update CURRENT_TIMESTAMP
);

However, this produced an error:

ERROR 1293 (HY000): Incorrect table definition; there can be only one TIMESTAMP column with CURRENT_TIMESTAMP in DEFAULT or ON UPDATE clause

What is the best way to do this?

I'm thinking stored procedure, but looking for a standard solution. I'm also concerned with access privileges -- as few programs/things should be able to touch the timestamps as possible.


Although I would prefer MySQL answers, solutions for other RDBMS's are also appreciated!

4

2 に答える 2

5

はい、これはMySQLの不十分な制限です。アプリケーションを使用している場合は、created_at 列に time() 呼び出しを追加し、updated_at 列に CURRENT_TIMESTAMP を使用させることができます。

$sql = "INSERT INTO my_table SET name = 'Mike', created_at = " . time();

updated_at 列ほど頻繁に触れられない可能性があるため、created_at 列でこれを行うことを選択します。

- 編集 -

さらに良いのは、MySQL の組み込みnow()関数を使用することです。このように、アプリケーション サーバーと mysql サーバーのタイムゾーンではなく、mysql サーバーのタイムゾーンだけを気にする必要があります。

$sql = "INSERT INTO my_table SET name = 'Mike', created_at = NOW()";
于 2011-12-03T00:39:10.133 に答える
2

トリガーを使用できます。アプリケーションでも値を設定できますが、設定するとデータベースによって上書きされます。

delimiter //
CREATE TRIGGER def_bef_update BEFORE UPDATE ON def FOR EACH ROW BEGIN
    SET NEW.modification = CURRENT_TIMESTAMP;
END//
delimiter ;

また、データを確認し、重要な変更がある場合にのみ変更日を更新するためにも使用できます。

于 2011-12-03T01:04:29.777 に答える