是否有可能有一个空的MySQL数字字段?

时间:2016-08-20 17:40:41

标签: mysql

我想在MySQL数字字段上有一个空字段。如果我将字段定义为允许NULL值,则默认为0.00。有时对于这个行项目,我更喜欢没有价值。我可能会创建一个不同的表来跟踪这几个项目,但此时我更喜欢一个表格解决方案。

2 个答案:

答案 0 :(得分:1)

因为您使用DEFAULT执行了此操作。不要这样做:

create table t1
(   id int auto_increment primary key,
    thing varchar(100) not null,
    anInt NUMERIC(5,2) NULL DEFAULT 0
);

insert t1(thing) values ('fish');
select * from t1;
+----+-------+-------+
| id | thing | anInt |
+----+-------+-------+
|  1 | fish  |  0.00 |
+----+-------+-------+

答案 1 :(得分:1)

在mysql 5.7.12上为我工作:

mysql> create table X (a double null);
Query OK, 0 rows affected (0.01 sec)

mysql> desc X;
+-------+--------+------+-----+---------+-------+
| Field | Type   | Null | Key | Default | Extra |
+-------+--------+------+-----+---------+-------+
| a     | double | YES  |     | NULL    |       |
+-------+--------+------+-----+---------+-------+
1 row in set (0.00 sec)

mysql> alter table X add column b int;
Query OK, 0 rows affected (0.01 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> desc X;
+-------+---------+------+-----+---------+-------+
| Field | Type    | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| a     | double  | YES  |     | NULL    |       |
| b     | int(11) | YES  |     | NULL    |       |
+-------+---------+------+-----+---------+-------+
2 rows in set (0.00 sec)

mysql> insert into X (a) values (1.3);
Query OK, 1 row affected (0.00 sec)

mysql> insert into X (b) values (1);
Query OK, 1 row affected (0.00 sec)

mysql> select * from X;
+------+------+
| a    | b    |
+------+------+
|  1.3 | NULL |
| NULL |    1 |
+------+------+
2 rows in set (0.00 sec)
相关问题