如何防止在为一列更新 NOW() 时同时更新两个 NOW() 列

How to prevent two NOW() columns updated at the same time when update a NOW() for one column

我有一个 table 需要两个不同的当前时间。 首先,我有一个用于插入 actionnumber、msgSentFrom_F_ID、msgSentTo_M_ID 和 sentDate 的插入过程。 其次,用于更新 respondDate 的更新过程。 我的问题是,当我更新 respondDate 时,sentDate 会在我更新 respondDate 的同时更新。我哪里做错了? (我的目的是我希望 sentDate 是我插入时的当前时间,以及我更新 respondDate 时的另一个当前时间。)

CREATE TABLE IF NOT EXISTS actions (
  actionnumber INT AUTO_INCREMENT PRIMARY KEY,
  msgSentFrom_F_ID INT, 
  msgSentTo_M_ID INT,
  sentDate TIMESTAMP,
  respondDate TIMESTAMP NULL,
  FOREIGN KEY (msgSentFrom_F_ID) 
    REFERENCES femaleUsers(femaleuserId)
  FOREIGN KEY (msgSentTo_M_ID) 
    REFERENCES maleUsers(maleuserId)
);

DELIMITER //
create procedure (param_F_ID INT,param_M_ID INT,Sdate TIMESTAMP)
  BEGIN
  INSERT INTO actions (msgSentFrom_F_ID, msgSentTo_M_ID, sentDate) 
    VALUES (param_F_ID,param_M_ID,Now());
  END; //
DELIMITER ;

CALL insert_actions ('5','5',NOW());

DELIMITER //
create procedure update_respondDate (param_ActionNum INT, 
    param_respondDate TIMESTAMP)
  BEGIN
  UPDATE actions set respondDate = param_respondDate 
  WHERE  actionnumber = param_ActionNum;
  END; //
DELIMITER ;

CALL update_respondDate('6',NOW());

听起来您禁用了系统变量 explicit_defaults_for_timestampdocumentation 解释了这个结果:

If the explicit_defaults_for_timestamp system variable is disabled, the first TIMESTAMP column has both DEFAULT CURRENT_TIMESTAMP and ON UPDATE CURRENT_TIMESTAMP if neither is specified explicitly. To suppress automatic properties for the first TIMESTAMP column, use one of these strategies:

  • Enable the explicit_defaults_for_timestamp system variable. In this case, the DEFAULT CURRENT_TIMESTAMP and ON UPDATE CURRENT_TIMESTAMP clauses that specify automatic initialization and updating are available, but are not assigned to any TIMESTAMP column unless explicitly included in the column definition.

  • Alternatively, if explicit_defaults_for_timestamp is disabled, do either of the following:

    • Define the column with a DEFAULT clause that specifies a constant default value.

    • Specify the NULL attribute. This also causes the column to permit NULL values, which means that you cannot assign the current timestamp by setting the column to NULL. Assigning NULL sets the column to NULL, not the current timestamp. To assign the current timestamp, set the column to CURRENT_TIMESTAMP or a synonym such as NOW().

由于 sentDate 是 table 中的第一个 TIMESTAMP 列,只要您对该行进行任何更改,它就会自动设置为当前时间。