MySQL建表设置默认值/取值范围

一、设置默认值

设置默认值采用default,如代码所示:

二、设置取值范围

设置取值范围采用check,如代码所示:

create table student(
id int not null  primary key auto_increment,
name varchar(32) not null,
sex varchar(8) default('男'), #设置默认值
age int not null check (age between 10 and 50), #设置取值范围
class_id int not null references class(id),
stu_num varchar(32),
constraint stu_u unique(stu_num)
);

MySQL创建表时字符串的默认值

使用MySQL创建表时,char或varchar类型的变量可以设置默认值null或Empty String。

MySQL建表设置默认值/取值范围的操作代码

操作:

创建如下DDL格式的一张表:

MySQL建表设置默认值/取值范围的操作代码

执行以下insert语句,观察char和varchar类型的默认值:

insert into t_table(iddddd) values(11);

产生如下表数据:

MySQL建表设置默认值/取值范围的操作代码

结论:

第一,null和Empty String是两种不同的数据,字段id3和id6中存放的是”“空字符串。

第二,如果手动在Navicat里面改变了id、id2、id4、id5中的值,那么尽管删除所做的改变,字段的值不会恢复到之前的null,而是变成了Empty String “”。比如先将字段id的值变成aaa,后来又删除,此时字段id的值为Empty String “”。

MySQL建表设置默认值/取值范围的操作代码

当然使用以下update语句可以恢复到id=null

update t_table set id=null where iddddd=11;

MySQL建表设置默认值/取值范围的操作代码

第三,在对非空进行查询的时候,最好对null和Empty String “”都做判断。例如对于Hibernate的QBC查询可以加上两个限制条件:

Restrictions.isNotNull("propertyName") // 判断不为null
Restrictions.ne("propertyName") // 判断不为""
原文地址:https://blog.csdn.net/HBT036017/article/details/110087858

相关文章:

  • 2021-11-08
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-01-13
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-09-06
  • 2021-12-10
  • 2021-08-16
  • 2021-06-15
  • 2021-06-14
  • 2021-09-20
相关资源
相似解决方案