首页 > 解决方案 > 如果字段为空则更新,否则忽略

问题描述

如果和存在于表中,我正在尝试更新该test_cert_date字段,否则需要插入该行。batch_idsr_noinq_prod_dates

例子:

inq_prod_dates :

ID batch_id sr_no test_cert_date
1 2 3 20-05-2021
2 4 4
  1. 如果将batch_idas 2 和sr_noas 3 传递给 mysql 查询,则需要检查该test_cert_date字段在 table 中是否具有此组合的任何值,如果 value 为空则只需要执行更新,否则忽略。

  2. 如果表中不存在batch_idandsr_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_idandsr_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)

标签: mysql

解决方案


通过添加复合唯一键来解决问题,如下所示:

ADD UNIQUE KEY `batch` (`batch_id`,`sr_no`) USING HASH;

推荐阅读