mysql - 仅当日期时间为空时才更新 mysqli

标签 mysql sql-update

我有一个任务。仅当日期时间列为空时,系统才应更新该列。

我有这个查询

update posts set name = '$name', pubdate = case when pubdate is null 
then now()
else pubdate end 
where id = '$postid'

这是正确的方法吗?还有其他更好的解决方案吗?

最佳答案

你的逻辑很好。我可能会更简洁地写为:

update posts
    set name = '$name',
        pubdate = coalesce(pubdate, now())
    where id = '$postid';

注释:

  • 如果 ID 是数字,请勿将该值放在单引号中。
  • 更重要的是,$name$postid 应该是查询的参数,而不是直接插入到查询字符串中。

关于mysql - 仅当日期时间为空时才更新 mysqli,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38293527/

相关文章:

mysql - 在 if 语句 shell 脚本中运行 sql 查询

mysql - 在 MySQL 的存储过程中错误使用 UPDATE、REPEAT 和 LIMIT

使用内连接更新 DB2

MySql Update Join 两个表 SET CASE 无效组函数

sql - 基本 Postgres : How do I insert a value into all rows?

mysql - 将 MySQL 表转换为 Cassandra 中的 ColumnFamily : Slow batch mutations with Hector

mysql - SQL - 过滤两列

PHP password_verify 返回 false

mysql - 如何在mysql中获取月份的周平均值?

mysql - 使用多个值更新和 CONCAT