在mysql中添加两个自动更新的timestamp字段
时间:2009-07-01 来源:sss0213
在MySql 5.0 的表里同时添加两个自动更新的timestamp字段
有时我们需要在一张表里实现两种timestamp属性的字段,一种是在insert的时候自动赋值,另一种是在update时候赋值,但是在,mysql5.0里面这两种字段十户无法共存,比如你在创建者张表时:
java 代码
TIMESTAMP column with CURRENT_TIMESTAMP in DEFAULT or ON UPDATE clause
解决办法是使用trigger,首先将上面新建表格的语句改成以下内容:
java 代码
java 代码
java 代码
java 代码
有时我们需要在一张表里实现两种timestamp属性的字段,一种是在insert的时候自动赋值,另一种是在update时候赋值,但是在,mysql5.0里面这两种字段十户无法共存,比如你在创建者张表时:
java 代码
- CREATE TABLE blog_entries (
- `published` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
- `updated` TIMESTAMP DEFAULT '0000-00-00 00:00:00' ON UPDATE CURRENT_TIMESTAMP,
- `title` VARCHAR(128)
- );
TIMESTAMP column with CURRENT_TIMESTAMP in DEFAULT or ON UPDATE clause
解决办法是使用trigger,首先将上面新建表格的语句改成以下内容:
java 代码
- CREATE TABLE blog_entries (
- `published` TIMESTAMP DEFAULT '0000-00-00 00:00:00',
- `updated` TIMESTAMP DEFAULT '0000-00-00 00:00:00',
- `title` VARCHAR(128)
- );
java 代码
- CREATE TRIGGER blog_entries_publish BEFORE INSERT ON `blog_entries`
- FOR EACH ROW SET NEW.published = NOW(), NEW.updated = '0000-00-00 00:00:00';
- CREATE TRIGGER blog_entries_update BEFORE UPDATE ON `blog_entries`
- FOR EACH ROW SET NEW.updated = NOW(), NEW.published = OLD.published;
java 代码
- CREATE TABLE blog_entries (
- `published` TIMESTAMP NULL DEFAULT NULL,
- `updated` TIMESTAMP NULL DEFAULT NULL,
- `title` VARCHAR(128)
- );
- CREATE TRIGGER blog_entries_publish BEFORE INSERT ON `blog_entries` FOR EACH ROW SET
- NEW.published = IFNULL(NEW.published, NOW()),
- NEW.updated = IFNULL(NEW.updated, '0000-00-00 00:00:00');
- CREATE TRIGGER blog_entries_update BEFORE UPDATE ON `blog_entries` FOR EACH ROW SET
- NEW.updated = IF(NEW.updated = OLD.updated OR NEW.updated IS NULL, NOW(), NEW.updated),
- NEW.published = IFNULL(NEW.published, OLD.published);
java 代码
- CREATE TRIGGER blog_entries_update BEFORE UPDATE ON `blog_entries` FOR EACH ROW SET
- NEW.updated = CASE
- WHEN NEW.updated IS NULL THEN OLD.updated
- WHEN NEW.updated = OLD.updated THEN NOW()
- ELSE NEW.updated
- END,
- NEW.published = IFNULL(NEW.published, OLD.published);
相关阅读 更多 +