【问题标题】:How to update only those who are divisible MySQL如何只更新那些可整除的 MySQL
【发布时间】:2020-10-15 13:54:26
【问题描述】:
update comments
set comment = case
    when id % 7 = 0 then 'The universe is such an amazing thing.'
    when id % 5 = 0 then 'I definitely read the article again.'
    when id % 3 = 0 then 'This is interesting.'
    when id % 2 = 0 then 'Very good article'
end
where id between 1 and 15;

它给了我错误:错误代码:1048。“评论”列不能为空! 我只想更新那些可以整除的女巫。 所有其他不可分割的我想保持不变。

【问题讨论】:

  • id 等于11 或13 时,when 子句都不成立,那么comment 等于什么?您要么需要更多 when 子句或 else 子句。

标签: mysql sql sql-update case


【解决方案1】:

您可以将else 分支添加到case 表达式,当它不匹配任何除数时保持注释不变:

update comments
set comment = case
    when id % 7 = 0 then 'The universe is such an amazing thing.'
    when id % 5 = 0 then 'I definitely read the article again.'
    when id % 3 = 0 then 'This is interesting.'
    when id % 2 = 0 then 'Very good article'
    else comment
end
where id between 1 and 15;

或者您可以使用where 条件:

update comments
set comment = case
    when id % 7 = 0 then 'The universe is such an amazing thing.'
    when id % 5 = 0 then 'I definitely read the article again.'
    when id % 3 = 0 then 'This is interesting.'
    when id % 2 = 0 then 'Very good article'
end
where 
    id between 1 and 15
    and (id % 2 = 0 or id % 3 = 0 or id % 5 or id % 7 = 0)

如果您真的要过滤 1 到 15 之间的值,那么这可以简化:

 where id between 1 and 15 and id not in (1, 11, 13)

【讨论】:

    【解决方案2】:

    您的“案例”并未描述所有可能的案例。

    13 不是 0 %7、%5、%3 也不是 %2。

    最好的做法是添加一个default 案例来捕获这些场景,在 SQL 语言中标记为 else

    【讨论】:

    • 这就是我要问的。如何让它们保持原样,只改变那些可分而无余的。这是一个考试练习。
    • 当时我不明白你的问题(你选择的答案让我明白你的练习)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-01
    相关资源
    最近更新 更多