重复密钥更新的MySQL没有更新

问题描述 投票:0回答:1

我正在尝试使用重复密钥更新,但它不会影响任何行。

我的表创建语句,您可以看到我在childid和date上创建了一个唯一键。

CREATE TABLE `history_childfees` (
    `childid` int(11) DEFAULT NULL,
    `date` date DEFAULT NULL,
    `amount` decimal(10,2) DEFAULT NULL,
    `feetypecode` varchar(45) DEFAULT NULL,
    UNIQUE KEY `key_childdate` (`childid`,`date`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

这是我在表中的两行。

enter image description here

我想要更新的行是第一行,通过在2019-03-22更改子86615的数量。

insert into history_childfees (childid,date,amount,feetypecode)
values(86615,'2019-03-22',50,'DAY')
on duplicate key update childid = 86615, date = '2019-03-22';

我也尝试过这种语法。

insert into history_childfees (childid,date,amount,feetypecode)
values (86615,'2019-03-22',50,'DAY')
on duplicate key update childid = values(childid), date = values(date);

无论哪种方式,它都不执行插入,并且在执行时没有错误,但它会影响0行。我在这里错过了什么?

mysql sql unique-key
1个回答
1
投票

考虑:

CREATE TABLE `history_childfees` (
    ...  
    UNIQUE KEY `key_childdate` (`childid`,`date`)
);

和:

insert into history_childfees
...
on duplicate key update childid = 86615, date = '2019-03-22'

您在重复键上更新的列正是您用于标识重复项的UNIQUE KEY列。根据设计,我们已经知道值匹配...因此,查询会保留未修改的重复记录。

如果我正确地跟着你,你可能想要:

insert into history_childfees
...
on duplicate key update amount = 50
© www.soinside.com 2019 - 2024. All rights reserved.