空字符串插入零,而不是空值
我的插入语句如下所示:
INSERT INTO foo (bar) VALUES ('');
bar
字段的创建方式如下:
bar INT(11)
COLLATION: (NULL)
NULL: YES
DEFAULT: (NULL)
MySQL 版本:5.1。
空字符串不应该插入NULL吗?我不确定为什么我看到表中存储了零 (0)。
My insert statement looks like this:
INSERT INTO foo (bar) VALUES ('');
The bar
field was created like so:
bar INT(11)
COLLATION: (NULL)
NULL: YES
DEFAULT: (NULL)
MySQL version: 5.1.
Shouldn’t an empty string insert a NULL? I’m not sure why I’m seeing a zero (0) being stored in the table.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
默认情况下,MySQL 会尝试将列的无效值强制为正确的类型。这里,空字符串
''
是字符串类型,它既不是整数也不是NULL。我建议采取以下步骤:INSERT INTO foo (bar) VALUES (NULL);
MySQL by default attempts to coerce invalid values for a column to the correct type. Here, the empty string
''
is of type string, which is neither an integer nor NULL. I suggest taking the following steps:INSERT INTO foo (bar) VALUES (NULL);
您没有将
NULL
插入表中;您正在插入一个空字符串(它显然作为 int 映射到零)。请记住,NULL
在 SQL 中是一个不同的值;NULL!=''
。通过指定任何值(NULL
除外),您不会插入NULL
。仅当您未指定值时才会使用默认值;在您的示例中,您为整数列指定了一个字符串值。You're not inserting
NULL
into the table; you're inserting an empty string (which apparently maps to zero as an int). Remember thatNULL
is a distinct value in SQL;NULL != ''
. By specifying any value (other thanNULL
), you're not insertingNULL
. The default only gets used if you don't specify a value; in your example, you specified a string value to an integer column.为什么它应该是 NULL?您提供的值具有整数表示形式:空字符串转换为
INT
0
。仅当您未提供任何值时,才会采用默认值。
Why should it be a NULL? You're providing a value that has an integer representation: empty strings convert to
INT
0
.Only if you didn't provide any value would the default take over.
做到这一点的方法是根本不填充该字段。只填充那些真正需要有值的部分。
The way to do this is to not fill the field at all. only fill the ones that actually need to have a value.