duan02468 2014-10-30 19:35
浏览 294
已采纳

在INSERT ON DUPLICATE KEY UPDATE中,检测指定插入值时是否使用默认值

suppose i have this query (in conjunction with PHP)

INSERT INTO table (field1, field2, field3) VALUES (a, $field2, c) ON DUPLICATE KEY UPDATE field2 = IF(VALUES(field2) [ends up using DEFAULT(field2)], field2, VALUES(field2))

where $field2 can either be

a. legitimate normal value to be inserted into field2 or b. The string "DEFAULT(field2)" which would insert whatever mysql default value of the field is (suppose default is 22)

now my goal is to make it so that on the UPDATE part of the query:

if case a.) occurred then update the column with the user specified $field2 value accordingly. othwerwise, if case b.) occurred then keep the row as it is (ie. don't modify the data)

basically i need to fill in the "[ends up using DEFAULT(field2)]" part of the query to accomplish the above

now my first impulse is to perform ON DUPLICATE KEY UPDATE field2 = IF(VALUES(field2) = DEFAULT(field2), field2, VALUES(field2))

but then this would also ends up keeping the row as it is for case a.) in which $field2 = 22 since 22 is the default value of the mysql hence VALUES(field2) = DEFAULT(field2) is TRUE despite the fact in case a.) we want 22 to be updated accordingly instead of keeping the current value

in other words, how do I modify this query so that it'll only perform the update if a value was explicitly inserted in, but don't perform the update if "DEFAULT(field2)" ends up being used

  • 写回答

1条回答 默认 最新

  • dsdioa9545 2014-10-31 15:19
    关注

    You can run MySQL in strict mode and set this column to NOT NULL definition. Then instead of trying to insert a default value into the column when this case is triggered, you can insert NULL. This would cause an error, causing the query to fail.

    I think this is a bit hacky though. I would need to understand your use case better to really see if you should be using a different call pattern altogether.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 对于知识的学以致用的解释
  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败