Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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 :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...