代码之家  ›  专栏  ›  技术社区  ›  Radu Maris

mysql update multiple columns with same now()

  •  75
  • Radu Maris  · 技术社区  · 14 年前

    mysql> update table set last_update=now(), last_monitor=now() where id=1;
    

    这是安全的,或者有可能列在不同的时间更新,因为对 now() ?
    我不认为它可以用不同的值来更新(我认为在内部mysql调用 每排一次或类似的),但我不是专家,你怎么看?

    第二个问题被提取出来 here

    7 回复  |  直到 5 年前
        1
  •  146
  •   Community CDub    4 年前

    找到了解决方案:

    mysql> UPDATE table SET last_update=now(), last_monitor=last_update WHERE id=1;
    

    我发现 this

    下面的语句将col2设置为当前(更新的)col1值,而不是原始的col1值。结果是col1和col2 具有相同的值。此行为与标准SQL不同。

    更新t1集合col1=col1+1,col2=col1;

        2
  •  7
  •   Cœur Gustavo Armenta    7 年前

    Mysql不是很聪明。如果要在多个update或insert查询中使用相同的时间戳,则需要声明一个变量。

    now() 函数,每次在另一个查询中调用当前时间戳时,系统都会调用它。

        3
  •  5
  •   Rich Andrews    6 年前

    当语句开始执行时,MySQL会对每条语句计算一次now()。因此,每个语句有多个visible now()调用是安全的。

    select now(); select now(), sleep(10), now(); select now();
    +---------------------+
    | now()               |
    +---------------------+
    | 2018-11-05 16:54:00 |
    +---------------------+
    1 row in set (0.00 sec)
    
    +---------------------+-----------+---------------------+
    | now()               | sleep(10) | now()               |
    +---------------------+-----------+---------------------+
    | 2018-11-05 16:54:00 |         0 | 2018-11-05 16:54:00 |
    +---------------------+-----------+---------------------+
    1 row in set (10.00 sec)
    
    +---------------------+
    | now()               |
    +---------------------+
    | 2018-11-05 16:54:10 |
    +---------------------+
    1 row in set (0.00 sec)
    
        4
  •  1
  •   Sachin Shanbhag    14 年前

    在运行update查询之前,可以将now()的值存储在变量中,然后使用该变量更新这两个字段 last_update last_monitor .

        5
  •  1
  •   blackpanther    11 年前

    您可以将以下代码放在timestamp列的默认值上: CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP

        6
  •  0
  •   blackpanther    11 年前

    如果你真的需要确定 now() update last_monitor = to last_update last_update (尚未更新)

    mysql> update table set last_update=now() where id=1;
    mysql> update table set last_monitor = last_update where id=1;
    

    不管怎样,我认为mysql足够聪明,可以要求 每次查询仅一次。

        7
  •  0
  •   Wahinya Brian    6 年前

    有两种方法可以做到这一点;

    ,我建议您在将now()注入sql语句之前将其声明为变量。让我们说;

    var x = now();
    mysql> UPDATE table SET last_update=$x, last_monitor=$x WHERE id=1;
    

    var y = time();
    mysql> UPDATE table SET last_update=$x, last_monitor=$y WHERE id=1;
    

    通过这种方式,您可以尽可能多地使用变量,不仅在mysql语句中,而且在您的项目中使用的服务器端脚本语言(如PHP)中。 记住,这些变量可以作为输入插入到应用程序前端的表单中。这使得项目是动态的,而不是静态的。

    如果now()表示更新时间,那么可以使用mysql将行的属性标记为时间戳。每次插入或更新行时,时间也会更新。