mysql - 如果字段为空则更新,否则忽略
问题描述
如果和存在于表中,我正在尝试更新该test_cert_date
字段,否则需要插入该行。batch_id
sr_no
inq_prod_dates
例子:
inq_prod_dates :
ID | batch_id | sr_no | test_cert_date |
---|---|---|---|
1 | 2 | 3 | 20-05-2021 |
2 | 4 | 4 |
如果将
batch_id
as 2 和sr_no
as 3 传递给 mysql 查询,则需要检查该test_cert_date
字段在 table 中是否具有此组合的任何值,如果 value 为空则只需要执行更新,否则忽略。如果表中不存在
batch_id
andsr_no
组合,则需要插入行。
CREATE TABLE `inq_prod_dates` (
`id` int(11) NOT NULL,
`batch_id` tinytext NOT NULL,
`sr_no` tinytext NOT NULL,
`test_cert_date` tinytext NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
我尝试使用以下查询,但即使表中存在batch_id
andsr_no
组合,也会插入新行。
INSERT INTO inq_prod_dates (batch_id, sr_no, test_cert_date)
VALUES('2', '3','20-05-2021')
ON DUPLICATE KEY UPDATE test_cert_date = IF(test_cert_date IS NULL, '20-05-2021', test_cert_date)
解决方案
通过添加复合唯一键来解决问题,如下所示:
ADD UNIQUE KEY `batch` (`batch_id`,`sr_no`) USING HASH;
推荐阅读
- python - 为什么将 GNN 与 dgl 异形图一起使用会遇到行数据不匹配错误?
- java - okhttp 客户端在 # 符号处截断 http URL
- django - 编辑多选字段?
- python - 如何在 Django 中保存静态/类变量
- r - 应用 weighted.mean() 不会影响结果?
- java - 无法加载类“com.squareup.javawriter.JavaWriter”
- nlp - 如何准备数据以使用新语言从头开始训练 GPT 模型
- javascript - CSS动画属性不适用于位置元素
- php - 你知道为什么按钮没有出现吗?
- debugging - 为什么 Slime 的调试器没有在选定的帧中评估这个特定的表达式?