mysql enum 为空查询_MySQL中的枚举是否需要为非NULL?

bd96500e110b49cbb3cd949968f18be7.png

Lets say I have this:

ALTER TABLE asdf ADD field ENUM('Y', 'N') DEFAULT 'N';

Is putting a NOT NULL on the end necessary as it can only be Y and N?

EDT: based on comments, if I know the software always sets it to 'N' or 'Y' and is hardcoded in then is it OK to leave it off or could it still potentially become null some how.

解决方案

MySQL will allow the value to be NULL if you do not specify NOT NULL in the column definition.

Here's a quick test:

mysql> create table test (id serial, field ENUM('Y','N') DEFAULT 'N');

Query OK, 0 rows affected (0.01 sec)

mysql> INSERT INTO test (field) VALUES ('Y');

Query OK, 1 row affected (0.00 sec)

mysql> INSERT INTO test (field) VALUES ('N');

Query OK, 1 row affected (0.00 sec)

mysql> INSERT INTO test () VALUES ();

Query OK, 1 row affected (0.00 sec)

mysql> INSERT INTO test (field) VALUES (NULL);

Query OK, 1 row affected (0.00 sec)

mysql> INSERT INTO test (field) VALUES ('Invalid');

Query OK, 1 row affected, 1 warning (0.01 sec)

mysql> show warnings;

+---------+------+--------------------------------------------+

| Level | Code | Message |

+---------+------+--------------------------------------------+

| Warning | 1265 | Data truncated for column 'field' at row 1 |

+---------+------+--------------------------------------------+

1 row in set (0.00 sec)

mysql> select * from test;

+----+-------+

| id | field |

+----+-------+

| 1 | Y |

| 2 | N |

| 3 | N |

| 4 | NULL |

| 5 | |

+----+-------+

5 rows in set (0.00 sec)

So MySQL does respect the default value, but also allows NULLs. (Interestingly, it will truncate invalid values and allow blank strings as well, but that's a different issue)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值