0

我在一个表中有一个列 disc_base_pct,我试图避免 NULL。但是,此表的记录来自另一个表,如果折扣不适用于它们,它们可能会使用 null。数据以这种方式从另一个表中插入:

insert into sandbox_1.table (id, conditions, base price, disc_base_pct)
select id, conditions, base price, disc_base_pct from user_1.table;

如果当前值不可能,我假设该列将设置为默认值。并且 0 值有一些实际意义,所以不能使用 0。最后,我将 disc_base_pct 列设置为 NOT NULL default -1,如下所示

 `disc_base_pct` decimal(7,4) NOT NULL DEFAULT '-1.0000',

我希望通过这种方式MySQL可以自动将NULL转换为默认值-1。但是当我测试它时,它不像我想象的那样工作。

首先,让我们将 disc_base_pct 值设置为 0.5。disc_base_pct 列类型设置为 (decimal(7,4) NOT NULL DEFAULT '-1.0000') 然后我运行下面的查询,

update sandbox_1.table
set disc_base_pct = null;

我会收到警告

1 row(s) affected, 1 warning(s): 1048 Column 'disc_base_pct' cannot be null Rows matched: 1  Changed: 1  Warnings: 1

之后,我从 temp_tbl_fc_fare_map 运行 select disc_base_pct;结果值显示 disc_base_pct 设置为 0 而不是默认值 -1。 请点击查看结果图

顺便说一句,@FaNo_FN 提到当我将 NULL 值更新为 NOT NULL 列时,我应该收到错误而不是警告。但我只是收到一条警告信息。是否涉及任何MySQL配置?</p>

当输入值为 NULL 时,有什么方法可以强制将 NOT NULL 列设置为默认值?

我得到了一个解决方案,将行恢复为默认列值 mysql。在我的场景中这将无济于事,因为如果 0 是源表中的可能值。如果表已经将 NULL 转换为 0,我将无法识别 0 是原始值还是 0 是从 NULL 转换而来的值。它有很大的不同。NULL 中的 0 表示不允许折扣,而原来的 0 可能表示它是免费产品的特殊事件。

但答案将表明输入部分的修改。它会起作用的。但我仍然想知道为什么默认值不起作用。

insert into sandbox_1.table (id, conditions, base price, disc_base_pct)
select id, conditions, base price, if(disc_base_pct is null, -1, disc_base_pct) from user_1.table;

最新更新:@FaNo_FN 感谢 FaNo_FN,看起来结果可能因 MySQL 版本而异。在我本地的 MySQL 8.0.13 中,它符合我在这个问题中的描述。但是,对于 MySQL 8.0.23 作为链接https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=05ca7b6c570080896d6d3136cc74dc5b,它将拒绝将值设置为 NULL

4

1 回答 1

2

The purpose of the default value is to set it when other fields in that row are set and the dict_base_pct wasn't. If you ran your query above, but without the disc_base_pct column, or it's value, the column would be populated with the default. Ex:

insert into sandbox_1.table (id, conditions, base price) 
select id, conditions, base price from user_1.table;

And, yes, depending on how sql_mode is set you will get either a warning or an error when trying to insert an invalid value. If you are inserting from a select statement you might also look into one of the following functions:

  • if (like you showed in your question)
  • case
  • ifnull
  • coalesce
于 2021-02-25T19:22:54.530 回答