创建表UP

1
2
3
4
5
create table 表名(
字段1 字段1数据类型 字段1约束条件,
字段2 字段2数据类型 字段2约束条件,
字段3 字段3数据类型 字段3约束条件
);

约束条件

NOT NULL

非空约束,用于约束该字段的值不能为空。

DEFAULT

默认值约束,用于约束该字段有默认值,约束当数据表中某个字段不输入值时,自动为其添加一个已经设置好的值。

PRIMARY KEY

主键约束,用于约束该字段的值具有唯一性,至多有一个,可以没有,并且非空。

UNIQUE

唯一约束,用于约束该字段的值具有唯一性,可以有多个,可以没有,可以为空。

FOREIGN KEY

外键约束,外键约束经常和主键约束一起使用,用来确保数据的一致性,用于限制两个表的关系,用于保证该字段的值必须来自于主表的关联列的值。在从表添加外键约束,用于引用主表中某列的值。

CHECK

检查约束,用来检查数据表中,字段值是否有效。

例如:
创建一个hello3表
hello_id 为自增的主键
hello_key 为主键
hello_uname 是唯一的
hello_pwd 不能为空
hello_age 默认值为1
hello_scores 范围为0到100之间
hello_time 默认为当前时间(到天为止)
createtime 默认当前时间(到秒为止)

1
2
3
4
5
6
7
8
9
10
11
create table hello3 (
hello_id int AUTO_INCREMENT,
hello_key varchar(20),
hello_uname varchar(20) unique,
hello_pwd varchar(20) not null,
hello_age int default 1,
hello_scores int check(hello_scores>=0 and hello_scores<=100),
hello_time date default (curdate()),
createtime timestamp NULL default CURRENT_TIMESTAMP,
primary key(hello_id,hello_key)
);

AUTO_INCREMENT 自增
primary key 主键
curdate() 当前时间到天为止
CURRENT_TIMESTAMP 当前时间到秒为止
unique 唯一约束

插入数据(成功)

1
INSERT INTO hello3(hello_key,hello_uname,hello_pwd,hello_scores)VALUES("1","张三","112233",66);

插入数据(失败,因为hello_uname有唯一约束)

1
INSERT INTO hello3(hello_key,hello_uname,hello_pwd,hello_scores)VALUES("2","张三","123456",77);

插入数据(失败,因为hello_key和hello_id是主键不能重复(但因为有2主键当一个主键值不一样另一个主键一样也是可以插入的,单主键的话不行))

1
INSERT INTO hello3(hello_id,hello_key,hello_uname,hello_pwd,hello_scores)VALUES(1,"1","李四","123455",88);

在上表的基础上创建有外键的表hello4
hello_id 为hello3的外键
hello_key 为hello3的外键
after_time 比当前时间迟一年(到天为止)
after_createtime 比当前时间迟一年(到秒为止)(时分秒会被重置为 00:00:00)

1
2
3
4
5
6
7
8
create table hello4(
hello_id int not null,
hello_key varchar(20),
after_time date default (current_date + interval 1 year),
after_createtime timestamp default (current_date + interval 1 year),
PRIMARY KEY(hello_key,hello_id),
FOREIGN KEY(hello_id,hello_key) REFERENCES hello3(hello_id,hello_key)
);

插入数据(成功)(若你插入失败则查看一下hello3的hello_key与hello_id是否与当前插入的一致)

1
INSERT INTO hello4(hello_id,hello_key)VALUES(1,"1");

正则表达

REGEXP

符号 描述
. 匹配任意单个字符。
^ 匹配字符串的开始。
$ 匹配字符串的结束。
* 匹配零个或多个前面的元素。
+ 匹配一个或多个前面的元素。
? 匹配零个或一个前面的元素。
[abc] 匹配字符集中的任意一个字符。
[^abc] 匹配除了字符集中的任意一个字符以外的字符。
[a-z] 匹配范围内的任意一个小写字母。
[0-9] 匹配一个数字字符。
\w 匹配一个字母数字字符(包括下划线)。
\s 匹配一个空白字符。

例如:(创建一个hello表 字段phone类型为varchar长度为11的,且检查约束为11位,每位为数字(0-9))

1
2
3
4
create table hello (
phone varchar(11),
check (phone REGEXP '^[0-9]{11}$')
);

当执行语句

1
INSERT INTO hello(phone) VALUES("12345678910");

能成功插入,但若执行

1
INSERT INTO hello(phone) VALUES("12345c78910");

插入失败,因为检查约束为11位,每位为数字(0-9),而这条语句中含有c不符合检查约束条件,故而插入失败。

例如:(创建一个hello1表 字段age类型为int默认值为1,字段email类型为varchar长度为20的,需要包含@与.)

1
2
3
4
5
6
CREATE TABLE hello1 (
age int default 1,
email VARCHAR(20),
CHECK (email REGEXP '^.+@.+\\.[a-zA-Z]{2,}$')
);

执行插入语句

1
INSERT INTO hello1(email)values("11afafga@qq.com");

插入成功email为11afafga@qq.com,age为1(因为age设置了默认值1)