mysql - NULL在mysql中默认为空字符串?

标签 mysql sql

我有一个不允许 NULL 值的字段的奇怪情况。如果我插入一行,该字段默认为空字符串,即使 mysql 声称默认值为 NULL。

mysql> describe user;
+---------------------------+------------------+------+-----+---------+----------------+
| Field                     | Type             | Null | Key | Default | Extra          |
+---------------------------+------------------+------+-----+---------+----------------+
| id                        | int(30)          | NO   | PRI | NULL    | auto_increment |
| username                  | varchar(45)      | NO   | UNI | NULL    |                |
| city                      | varchar(45)      | NO   |     | NULL    |                |
+---------------------------+------------------+------+-----+---------+----------------+

mysql> show triggers;
Empty set (0.00 sec)

mysql> insert into user (username) values ('just_testing');
Query OK, 1 row affected, 17 warnings (0.01 sec)

这就是我要去的地方什么?! - city 应该默认为 NULL,这是不允许的,但请看这里:

mysql> select username, city from user where username = 'just_testing' and city is null;
Empty set (0.00 sec)

mysql> select username, city from user where username = 'just_testing' and city='';
+--------------+------+
| username     | city |
+--------------+------+
| just_testing |      |
+--------------+------+
1 row in set (0.00 sec)

Mysql 已经决定使用空字符串作为默认值,即使它不是这样并且没有任何触发器。

还有:

mysql> insert into user (username, city) values ('just_testing3', NULL);
ERROR 1048 (23000): Column 'city' cannot be null

我忽略了什么? city 列怎么默认为''?

最佳答案

来自docs :

If you are not running in strict SQL mode, any column not explicitly given a value is set to its default (explicit or implicit) value. For example, if you specify a column list that does not name all the columns in the table, unnamed columns are set to their default values. Default value assignment is described in Section 11.6, “Data Type Default Values”. See also Section 1.8.3.3, “Constraints on Invalid Data”.

further :

For string types other than ENUM, the default value is the empty string. For ENUM, the default is the first enumeration value.

关于mysql - NULL在mysql中默认为空字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31167878/

相关文章:

MySQL 5.5 - 选择记录更改的行

php - 两个 php 表单。第二种形式从第一种形式获取数据。但刷新第二页显示错误

Mysql存储过程在where子句中使用varchar变量的问题

mysql - 查询自定义元数据字段?

MYSQL如何限制join的结果

SQL/Hive 计数不同的列

php - 使用另一个 mysql/php 中一个表的数据

php - Code Igniter-批量插入功能在数据库中插入空字段

sql - Spring 命名参数JdbcTemplate : get the resulting SQL query with parameters substituted

android - Android 中的 SQL 参数化查询