SQL语句基本数据类型及约束条件
基本数据类型之日期相关
# 格式
date 年月日
datetime 年月日时分秒
time 时分秒
year 年
create table t1(id int comment "编号",
name varchar(32) comment "姓名",
data1 date comment "数据1",
data2 datetime comment "数据2",
data3 time comment "数据3",
data4 year comment "数据4");
mysql> insert into t1 values(1,"jason","2021-11-10","2021-11-10 19:54:28","19:54:28","2021");
Query OK, 1 row affected (0.08 sec)
mysql> select * from t1;
+------+-------+------------+---------------------+----------+-------+
| id | name | data1 | data2 | data3 | data4 |
+------+-------+------------+---------------------+----------+-------+
| 1 | jason | 2021-11-10 | 2021-11-10 19:54:28 | 19:54:28 | 2021 |
+------+-------+------------+---------------------+----------+-------+
1 row in set (0.00 sec)
# 注:comment无实际意义,类似于注释的说明
基本数据类型之枚举与集合类型
# 枚举
多选一 关键字"enum"
"提前定义好的数据后期录入只能按照之前输入的内容,比如说性别,提前规定好后,输入其他数据会报错"
create table t2(
id int,
name varchar(8),
gender enum("male","female","others")
);
insert into t2 values(1,"jason","male"); # 正常
insert into t1 values(2,'kevin','男'); # 报错
# 集合
多选 关键字"set"
create table t3(id int,
name char(8),
hobbies set("read","music","basketball","swimming"));
insert into t3 values(1,"jason","music,dance"); # 报错
insert into t3 values(2,"jason1","music,swimming"); # 正常
约束条件
# 创建表格的完整语句
create table 表名(
字段名称1 字段类型(数字) 约束条件,
字段名称2 字段类型(数字) 约束条件,
字段名称3 字段类型(数字) 约束条件
);
"约束条件相当于是在字段类型之上添加的额外约束(条件)"
1.unsigned # 无符号
id int unsigned #去除正负号
2.zero fill 用0填充
id int(5) zerofill # 当输入的id不足5位数是00001
3.not null # 非空
如果添加not null,不输入任何东西会报错
mysql> create table t4(id int not null,name varchar(24) not null);
mysql> insert into t4(id) values(1);
ERROR 1364 (HY000): Field 'id' doesn't have a default value # 报错
mysql> insert into t4(name) values("jason");
ERROR 1364 (HY000): Field 'name' doesn't have a default value # 报错
mysql> insert into t4 values(1,"jason");
Query OK, 1 row affected (1.83 sec) # 正确
4.default # 默认值
默认值(用户给了就用用户的 用户不给就是要默认的)
mysql> create table t5(id int,name varchar(12) default "匿名用户");
Query OK, 0 rows affected (0.35 sec)
mysql> insert into t5(id) values(1);
Query OK, 1 row affected (1.80 sec)
mysql> select * from t5;
+------+--------------+
| id | name |
+------+--------------+
| 1 | 匿名用户 |
+------+--------------+
1 row in set (0.00 sec)
mysql> insert into t5 values(1,"jason");