Mysql,一个列在更新后得到null值,怎么能不允许null在插入和更新



在这个表中,我希望标题列不允许null(不是空白)插入或更新行....用户应该100%为它插入一些值,以便生成行。

    create table tab(id int not null auto_increment
                 primary key,
                 title varchar(255) not null );
+-------+--------------+------+-----+---------+----------------+
| Field | Type         | Null | Key | Default | Extra          |
+-------+--------------+------+-----+---------+----------------+
| id    | int(11)      | NO   | PRI | NULL    | auto_increment |
| title | varchar(255) | NO   |     | NULL    |                |
+-------+--------------+------+-----+---------+----------------+

创建的表

现在我插入:

insert into tab (id, title) value (1, 'title1');真正…

插入选项卡(id)值(2 );.........................True ----- this不应该为null

mysql> select * from tab;
+----+--------+
| id | title  |
+----+--------+
|  1 | title1 |
|  2 |        |
+----+--------+
2 rows in set (0.00 sec)

title列添加NOT NULL约束,并删除default ''

导致default ''插入一个默认的空字符串的标题列,每当你没有为insert的标题列提供一个值。

所以,如果你的模式如下所示,插入值

create table tab(id int not null auto_increment
                 primary key,
                 title varchar(255) not null default '');
insert into tab(title) values('aaaaa'),('mmmmmm'),('');

然后尝试下面的查询,它将返回0行。因此,在title列中没有NULL值,而只有EMPTY STRING值。

select * from tab where title is null

你的模式应该如下所示,

create table tab(id int not null auto_increment
                 primary key,
                 title varchar(255) not null );

查看演示小提琴,如果你想进一步研究http://sqlfiddle.com/#!2/b5acf/3

最新更新