acxellencedk 发表于 2006-06-07 15:04

建表时,指定了not null,为什么还能用default ''

mysql> create table aaaaaaaaaa ( aaa varchar(64) not null default ' ');
Query OK, 0 rows affected (0.01 sec)

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

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


建完表后,可以插入两行值,都为空值,这和not null 相矛盾了啊。为什么?

yejr 发表于 2006-06-07 15:12

'' 是空字符串
NULL 跟它不一样
2者不同

acxellencedk 发表于 2006-06-07 15:23

null 不也是空吗?

null 不也是空吗?

bun 发表于 2006-06-07 15:48

rardge 发表于 2006-06-07 15:55

原帖由 acxellencedk 于 2006-6-7 15:23 发表
null 不也是空吗?

手册上特意举例告诉你 NULL 不是 '' 也不是 0。

mysql> SELECT 0 IS NULL, 0 IS NOT NULL, '' IS NULL, '' IS NOT NULL;
+-----------+---------------+------------+----------------+
| 0 IS NULL | 0 IS NOT NULL | '' IS NULL | '' IS NOT NULL |
+-----------+---------------+------------+----------------+
|         0 |             1 |          0 |            1 |
+-----------+---------------+------------+----------------+


你的字段定义为 not null,但是却赋值了一个 null,那么数据库系统会按照该字段类型选择一个默认的值放进去,比如 char 就是用空字符串。
但注意,空字符串其实已经是一个确定的值了,就是一个长度为 0 的字符串!

至于 NULL 值,给你一个正确的理解:把 NULL 理解为 UNKNOWN。
主要意思是'不知道',就是它可能是任何值;
另外一层意思是'信息缺失',比如某个存储姓名信息的字段值是 NULL,代表姓名信息缺失。
所以 NULL 值不是任意一个确定的值!

举例来说,逻辑 与/或 运算会的吧?
与运算:true and true = true, true and false = false, false and true = false, false and false = false

mysql> select true and null, false and null, null and null;
+---------------+----------------+---------------+
| true and null | false and null | null and null |
+---------------+----------------+---------------+
|          NULL |            0 |          NULL |
+---------------+----------------+---------------+

第一个 true and null,它的结果完全靠 null 确定。如果它是 true 结果就是 true,如果它是 false,结果就是 false。因为 null 代表不知道,所以结果也是不知道,所以是 null。

第二个 false and null,它的结果不需要靠 null 确定,因为 and 运算的特性,有 false 出 false,所以结果是 false。

第三个 null and null,就好理解了吧,它完全就是空对空了,两个操作数都是不知道,结果自然也是不知道,所以是 null。

同理你也可以用 或 运算来验证。

acxellencedk 发表于 2006-06-08 10:32

非常感谢!

非常感谢!我明白了!

xxjoyjn 发表于 2006-06-08 12:18

很有耐心,说的也很明白:em02::em02::em02:

rylynchen 发表于 2015-08-06 17:28

renxiao2003 发表于 2015-08-11 15:13

''不是NULL,两个含义都不一样的。
页: [1]
查看完整版本: 建表时,指定了not null,为什么还能用default ''