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 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛