【问题标题】:case when wont work with update statement不适用于更新语句的情况
【发布时间】:2020-04-27 01:15:48
【问题描述】:

对于我的 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


【解决方案1】:

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

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

Demo on dbfiddle

【讨论】:

    【解决方案2】:

    它将值设置为零,因为new_price = 100 是一个布尔表达式——其计算结果为 0 或 1。

    如果这就是你所做的一切,你应该在where 子句中过滤:

    update Products
        set new_price = 100
        where change_date > '2019-08-16';
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-28
      • 2023-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-22
      相关资源
      最近更新 更多