Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
565 views
in Technique[技术] by (71.8m points)

php - MySQL CURRENT_TIMESTAMP field updates on every update

The best way to explain this problem is with an example.

I have a table:

CREATE TABLE `example` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `data` varchar(255) DEFAULT NULL,
  `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8

Result:

   id  |  data  |       created       |       updated
 (NULL)| (NULL) |       (NULL)        |       (NULL)

Then I insert some data:

INSERT INTO example (
  `data`
) VALUES (
  'abc123'
)

Result:

  id  |  data  |       created       |       updated
   1  | abc123 | 2013-01-16 13:12:16 |       (NULL)

And then I update

UPDATE example SET 
  `data` = 'def456',
  `updated` = NOW()
WHERE id = 1

Result:

  id  |  data  |       created       |       updated
   1  | def456 | 2013-01-16 13:16:24 | 2013-01-16 13:14:26

The problem: Notice how the created field also updates and has a slightly different time to correctly saved updated field. I have set up this example table and others similarly on the same database without this problem, so I'm completely baffled by it.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

updated needs to be: TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP

So your CREATE TABLE would be:

CREATE TABLE `example` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `data` varchar(255) DEFAULT NULL,
  `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated` timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8

This means that when you perform your UPDATE in the future, you won't need to pass in an update variable because MySQL will automatically update it for you :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...