Having both a Created and Last Updated timestamp columns in MySQL 4.0

前端 未结 11 2191
逝去的感伤
逝去的感伤 2020-11-27 09:19

I have the following table schema;

CREATE TABLE `db1`.`sms_queue` (
  `Id` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
  `Message` VARCHAR(160) NOT NULL DEFAUL         


        
11条回答
  •  半阙折子戏
    2020-11-27 09:57

    This is how can you have automatic & flexible createDate/lastModified fields using triggers:

    First define them like this:

    CREATE TABLE `entity` (
      `entityid` int(11) NOT NULL AUTO_INCREMENT,
      `createDate` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
      `lastModified` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
      `name` varchar(255) DEFAULT NULL,
      `comment` text,
      PRIMARY KEY (`entityid`),
    )
    

    Then add these triggers:

    DELIMITER ;;
    CREATE trigger entityinsert BEFORE INSERT ON entity FOR EACH ROW BEGIN SET NEW.createDate=IF(ISNULL(NEW.createDate) OR NEW.createDate='0000-00-00 00:00:00', CURRENT_TIMESTAMP, IF(NEW.createDate
    • If you insert without specifying createDate or lastModified, they will be equal and set to the current timestamp.
    • If you update them without specifying createDate or lastModified, the lastModified will be set to the current timestamp.

    But here's the nice part:

    • If you insert, you can specify a createDate older than the current timestamp, allowing imports from older times to work well (lastModified will be equal to createDate).
    • If you update, you can specify a lastModified older than the previous value ('0000-00-00 00:00:00' works well), allowing to update an entry if you're doing cosmetic changes (fixing a typo in a comment) and you want to keep the old lastModified date. This will not modify the lastModified date.

提交回复
热议问题