在无法使用更新语句的情况下

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

对于我的MySQL查询,

update Products
set new_price = (
case when change_date>'2019-08-16' then new_price=100 else new_price end
)
;

更新语句将新价格设置为0。为什么?

表格详细信息:

insert into Products (product_id, new_price, change_date) values ('1', '20', '2019-08-14');
insert into Products (product_id, new_price, change_date) values ('2', '50', '2019-08-14');
insert into Products (product_id, new_price, change_date) values ('1', '30', '2019-08-15');
insert into Products (product_id, new_price, change_date) values ('1', '35', '2019-08-16');
insert into Products (product_id, new_price, change_date) values ('2', '65', '2019-08-17');
insert into Products (product_id, new_price, change_date) values ('3', '20', '2019-08-18');
select * from Products;
mysql sql sql-update case-when
2个回答
0
投票

您正在尝试将new_price设置为布尔表达式new_price=100的结果,除非0已经具有值new_price,否则它将为100。只需删除new_price=,代码即可正常工作:

update Products
set new_price = case when change_date>'2019-08-16' then 100
                     else new_price
                end

Demo on dbfiddle


0
投票

将值设置为零,因为new_price = 100是布尔表达式-且其值为0或1。

如果这是您要做的所有事情,则应在where子句中进行过滤:

update Products
    set new_price = 100
    where change_date > '2019-08-16';
© www.soinside.com 2019 - 2024. All rights reserved.