真正约束字段的是数据类型,但是数据类型约束很单一,需要有一些额外的约束,更好的保证数据的合法性,从业务逻辑角度保证数据的正确性。比如有一个字段是email,要求是唯一的。

表的约束很多,这里主要介绍如下几个: null/not null,default, comment, zerofill,primary key,
auto_increment,unique key 。

1.空属性

两个值:null和not null

当我们创建一个表时,默认里面的值是可以为空的。

mysql> create table myclass(
    -> classroom varchar(20),
    -> classname varchar(20));
Query OK, 0 rows affected (0.04 sec)

mysql> desc myclass;
+-----------+-------------+------+-----+---------+-------+
| Field     | Type        | Null | Key | Default | Extra |
+-----------+-------------+------+-----+---------+-------+
| classroom | varchar(20) | YES  |     | NULL    |       |
| classname | varchar(20) | YES  |     | NULL    |       |
+-----------+-------------+------+-----+---------+-------+
2 rows in set (0.01 sec)


使用desc查看时,可以发现里面的字段Null为YES,就代表可以设置为空。

mysql> insert into myclass values('一班',null);
mysql> select*from myclass;
+-----------+-----------+
| classroom | classname |
+-----------+-----------+
| 一班      | NULL      |
+-----------+-----------+
1 row in set (0.00 sec)

我们插入classname字段为空时,发现确实是为空的。

mysql> alter table myclass add student_number int;
Query OK, 0 rows affected (0.02 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> select*from myclass;
+-----------+-----------+----------------+
| classroom | classname | student_number |
+-----------+-----------+----------------+
| 一班      | NULL      |           NULL |
+-----------+-----------+----------------+
1 row in set (0.00 sec)

或者当我们新增一个字段的时候,已有的条目也会将这数据默认设置为null。

站在正常的业务逻辑中:

如果班级没有名字,你不知道你在哪个班级
如果教室名字可以为空,就不知道在哪上课

所以我们在设计数据库表的时候,一定要在表中进行限制,满足上面条件的数据就不能插入到表中。这就是“约束”。

对上述的表进行修改,直接修改是会出错的,因为表里面已经有数据为null,不可以直接将字段的属性设置为非空,需要将表里面的字段数据更新为非空才可以需改字段的属性为非空。

mysql> alter table myclass modify classname varchar(20) not null;
ERROR 1138 (22004): Invalid use of NULL value
//直接修改,报错

先更新字段的数据

mysql> update myclass set classname='102' where classroom='一班';
Query OK, 1 row affected (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> update myclass set student_number=55  where classroom='一班';
Query OK, 1 row affected (0.01 sec)
Rows matched: 1  Changed: 1  Warnings: 0

更新字段的属性

mysql> alter table myclass modify classroom varchar(20) not null;
Query OK, 0 rows affected (0.05 sec)

Records: 0  Duplicates: 0  Warnings: 0
mysql> alter table myclass modify classname varchar(20) not null;
Query OK, 0 rows affected (0.05 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> alter table myclass modify student_number int not null;
Query OK, 0 rows affected (0.05 sec)
Records: 0  Duplicates: 0  Warnings: 0

查看表字段属性

mysql> desc myclass;
+----------------+-------------+------+-----+---------+-------+
| Field          | Type        | Null | Key | Default | Extra |
+----------------+-------------+------+-----+---------+-------+
| classroom      | varchar(20) | NO   |     | NULL    |       |
| classname      | varchar(20) | NO   |     | NULL    |       |
| student_number | int         | NO   |     | NULL    |       |
+----------------+-------------+------+-----+---------+-------+
3 rows in set (0.00 sec)

之后插入的每一个字段都不可以为null了。

2.默认值

默认值:某一种数据会经常性的出现某个具体的值,可以在一开始就指定好,在需要真实数据的时候,用户可以选择性的使用默认值。

如果不设置默认值,默认值就为null。

mysql> create table tt1(
    -> name varchar(20) not null,
    -> age tinyint unsigned default 0,
    -> sex char(2) default '男');
Query OK, 0 rows affected (0.03 sec)

mysql> desc tt1;
+-------+------------------+------+-----+---------+-------+
| Field | Type             | Null | Key | Default | Extra |
+-------+------------------+------+-----+---------+-------+
| name  | varchar(20)      | NO   |     | NULL    |       |
| age   | tinyint unsigned | YES  |     | 0       |       |
| sex   | char(2)          | YES  |     | 男      |       |
+-------+------------------+------+-----+---------+-------+
3 rows in set (0.00 sec)

desc查看字段属性中的Default属性就是默认值了。

mysql> insert into tt1(name) values('小明');
Query OK, 1 row affected (0.01 sec)

mysql> select*from tt1;
+--------+------+------+
| name   | age  | sex  |
+--------+------+------+
| 小明   |    0 | 男   |
+--------+------+------+
1 row in set (0.00 sec)

之后我们如果要使用默认值的话,只要指定插入name字段就可以了。

mysql> insert into tt1(name) values('小明');
Query OK, 1 row affected (0.01 sec)

mysql> select*from tt1;
+--------+------+------+
| name   | age  | sex  |
+--------+------+------+
| 小明   |    0 | 男   |
+--------+------+------+
1 row in set (0.00 sec)

如果3个字段都设置了默认值的话,即插入空即可。

//修改第一个字段为默认值xxx
mysql> alter table tt1 modify name varchar(20) default 'xxx';
Query OK, 0 rows affected (0.04 sec)
Records: 0  Duplicates: 0  Warnings: 0

//插入空即可
mysql> insert into tt1 values();
Query OK, 1 row affected (0.01 sec)
mysql> select*from tt1;
+--------+------+------+
| name   | age  | sex  |
+--------+------+------+
| 小明   |    0 | 男   |
| xxx    |    0 | 男   |
+--------+------+------+
2 rows in set (0.00 sec)

3.列描述

列描述:comment,没有实际含义,专门用来描述字段,会根据表创建语句保存,用来给程序员或DBA来进行了。

mysql> create table tt12 (
-> name varchar(20) not null comment '姓名',
-> age tinyint unsigned default 0 comment '年龄',
-> sex char(2) default '男' comment '性别'
-> );
--注意:not null和defalut一般不需要同时出现,因为default本身有默认值,不会为空

通过desc看不到注释信息

mysql> desc tt2;
+-------+------------------+------+-----+---------+-------+
| Field | Type             | Null | Key | Default | Extra |
+-------+------------------+------+-----+---------+-------+
| name  | varchar(20)      | NO   |     | NULL    |       |
| age   | tinyint unsigned | YES  |     | 0       |       |
| sex   | char(2)          | YES  |     | 男      |       |
+-------+------------------+------+-----+---------+-------+
3 rows in set (0.00 sec)

可以通过show看到

mysql> show create table tt2;
+-------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table | Create Table                                                                                                                                                                                                                                  |
+-------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| tt2   | CREATE TABLE `tt2` (
  `name` varchar(20) NOT NULL COMMENT '姓名',
  `age` tinyint unsigned DEFAULT '0' COMMENT '年龄',
  `sex` char(2) DEFAULT '男' COMMENT '性别'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci        |
+-------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

4.zerofill

刚开始学习数据库时,很多人对数字类型后面的长度很迷茫。

创建tt3表:

mysql> create table tt3(
    -> a int(5) unsigned DEFAULT NULL,
    -> b int(5) unsigned DEFAULT NULL);
Query OK, 0 rows affected, 2 warnings (0.02 sec)

插入一条数据(没有加上zerofill属性):

mysql> insert into tt3 values(1,2);
Query OK, 1 row affected (0.00 sec)

mysql> select*from tt3;
+------+------+
| a    | b    |
+------+------+
|    1 |    2 |
+------+------+

这个时候有一个问题了?在建表的时候,int(5)后面的5是什么意思呢?如果要是没有设置zerofill属性,后面的5是没有用处的。

对字段a添加zerofill属性,显示的结果就有所不同了。

mysql> alter table tt3 change a a int(5) unsigned zerofill;
Query OK, 0 rows affected, 2 warnings (0.02 sec)
Records: 0  Duplicates: 0  Warnings: 2

mysql> select*from tt3;
+-------+------+
| a     | b    |
+-------+------+
| 00001 |    2 |
+-------+------+
1 row in set (0.00 sec)

这次可以看到a的值由原来的1变成00001,这就是zerofill属性的作用,如果宽度小于设定的宽度(这里设置的是5),自动填充0。要注意的是,这只是最后显示的结果,在MySQL中实际存储的还是1。

5.主键

主键:primary key用来唯一的约束该字段里面的数据,不能重复,不能为空,一张表中最多只能有一个主键;主键所在的列通常是整数类型。

 创建表的时候直接在字段上指定主键。

mysql> create table tt13 ( id int unsigned primary key comment '学号不能为空',  name varchar(20) not null);
Query OK, 0 rows affected (0.02 sec)
mysql> desc tt13;
+-------+--------------+------+-----+---------+-------+
| Field | Type         | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+-------+
| id    | int unsigned | NO   | PRI | NULL    |       |
| name  | varchar(20)  | NO   |     | NULL    |       |
+-------+--------------+------+-----+---------+-------+
2 rows in set (0.01 sec)

可以看到在key列中有一个PRI,表示为主键。

主键约束:主键对应的字段中不能重复,一旦重复,操作失败。

创建一个没有主键的表

mysql> create table tt14 ( id int unsigned comment '学号不能为空',  name varchar(20) not null);
Query OK, 0 rows affected (0.02 sec)

mysql> desc tt14;
+-------+--------------+------+-----+---------+-------+
| Field | Type         | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+-------+
| id    | int unsigned | YES  |     | NULL    |       |
| name  | varchar(20)  | NO   |     | NULL    |       |
+-------+--------------+------+-----+---------+-------+
2 rows in set (0.00 sec)

追加主键

mysql> alter table tt14 add primary key(id);
Query OK, 0 rows affected (0.05 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> desc tt14;
+-------+--------------+------+-----+---------+-------+
| Field | Type         | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+-------+
| id    | int unsigned | NO   | PRI | NULL    |       |
| name  | varchar(20)  | NO   |     | NULL    |       |
+-------+--------------+------+-----+---------+-------+
2 rows in set (0.00 sec)

可以看到追加主键后,表里面就拥有了主键,同时也会将Null的属性改为NO,因为主键是不能为空的。

删除主键:

mysql> alter table tt14 drop primary key;
Query OK, 0 rows affected (0.06 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> desc tt14;
+-------+--------------+------+-----+---------+-------+
| Field | Type         | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+-------+
| id    | int unsigned | NO   |     | NULL    |       |
| name  | varchar(20)  | NO   |     | NULL    |       |
+-------+--------------+------+-----+---------+-------+
2 rows in set (0.00 sec)

5.1 复合主键

也可以使用多个字段共同组成一个主键。

mysql> create table tt15(
    -> id int unsigned,
    -> course char(10) comment '课程代码',
    -> score tinyint unsigned default 60 comment '成绩',
    -> primary key(id,course));
Query OK, 0 rows affected (0.03 sec)

mysql> desc tt15;
+--------+------------------+------+-----+---------+-------+
| Field  | Type             | Null | Key | Default | Extra |
+--------+------------------+------+-----+---------+-------+
| id     | int unsigned     | NO   | PRI | NULL    |       |
| course | char(10)         | NO   | PRI | NULL    |       |
| score  | tinyint unsigned | YES  |     | 60      |       |
+--------+------------------+------+-----+---------+-------+
3 rows in set (0.00 sec)

使用id和course共同作为主键,之后插入的值拿这两个值来共同进行比较,只有全部相同才冲突。

6. 自增长

auto_increment:当对应的字段,不给值,会自动的被系统触发,系统会从当前字段中已经有的最大值+1操作,得到一个新的不同的值。通常和主键搭配使用,作为逻辑主键。

自增长的特点:

  1. 任何一个字段要做自增长,前提是本身是一个索引(key一栏有值)
  2. 自增长字段必须是整数
  3. 一张表最多只能有一个自增长

创建一个表,将id属性设为主键,同时设置主键为自增属性。

mysql> create table tt16( id int unsigned primary key auto_increment, name varchar(20) comment '学生名字');
Query OK, 0 rows affected (0.02 sec)

mysql> desc tt16;
+-------+--------------+------+-----+---------+----------------+
| Field | Type         | Null | Key | Default | Extra          |
+-------+--------------+------+-----+---------+----------------+
| id    | int unsigned | NO   | PRI | NULL    | auto_increment |
| name  | varchar(20)  | YES  |     | NULL    |                |
+-------+--------------+------+-----+---------+----------------+
2 rows in set (0.00 sec)

插入两个值:

mysql> insert into tt16(name) values('小明');
Query OK, 1 row affected (0.02 sec)

mysql> insert into tt16(name) values('小红');
Query OK, 1 row affected (0.01 sec)

mysql> select*from tt16;
+----+--------+
| id | name   |
+----+--------+
|  1 | 小明   |
|  2 | 小红   |
+----+--------+
2 rows in set (0.00 sec)

有了自增属性后,可以不需要插入主键的值,当插入的主键对应的字栏不给值时,主键的值会从主键最大的值开始在每次插入数据时自增。

mysql> insert into tt16 values(
    -> 1000,'小黑');
Query OK, 1 row affected (0.00 sec)

mysql> select*from tt16;
+------+--------+
| id   | name   |
+------+--------+
|    1 | 小明   |
|    2 | 小红   |
| 1000 | 小黑   |

上述主键的最大值为1000,那么下一次自增后的属性就是1001。

mysql> insert into tt16(name) values('小白');
Query OK, 1 row affected (0.01 sec)

mysql> select*from tt16;
+------+--------+
| id   | name   |
+------+--------+
|    1 | 小明   |
|    2 | 小红   |
| 1000 | 小黑   |
| 1001 | 小白   |
+------+--------+
4 rows in set (0.00 sec)

7.唯一键

一张表中有往往有很多字段需要唯一性,数据不能重复,但是一张表中只能有一个主键:唯一键就可以解决表中有多个字段需要唯一性约束的问题。

唯一键的本质和主键差不多,唯一键允许为空,而且可以多个为空,空字段不做唯一性比较。

关于唯一键和主键的区别:

我们可以简单理解成,主键更多的是标识唯一性的。而唯一键更多的是保证在业务上,不要和别的信息出现重复。

比如一个人的信息,选择身份证为主键了,那电话号码也需要维护唯一性。

创建方法和主键差不多,在后面加上unique key。

mysql> create table student2( id char(10) unique key comment '学号,不能重复,但是可以为空', name varchar(10));
Query OK, 0 rows affected (0.02 sec)

mysql> desc student2;
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| id    | char(10)    | YES  | UNI | NULL    |       |
| name  | varchar(10) | YES  |     | NULL    |       |
+-------+-------------+------+-----+---------+-------+
2 rows in set (0.00 sec)

key属性中由UNI,表示唯一键。

unique key键可以为空

mysql> insert into student2 values( null,'小黑');
Query OK, 1 row affected (0.01 sec)

mysql> select*from student2;
+------+--------+
| id   | name   |
+------+--------+
| NULL | 小黑   |
+------+--------+
1 row in set (0.00 sec)

唯一键相同时就会报错,禁止插入了。

mysql> insert into student2 values( 1,'小白');
Query OK, 1 row affected (0.01 sec)

mysql> insert into student2 values( 1,'小红');
ERROR 1062 (23000): Duplicate entry '1' for key 'student2.id'

8.外键

外键用于定义主表和从表之间的关系:外键约束主要定义在从表上,主表则必须是有主键约束或unique约束。当定义外键后,要求外键列数据必须在主表的主键列存在或为null。

//语法:
foreign key (字段名) references 主表(列)

先创建主表:

create table myclass (
id int primary key,
name varchar(30) not null comment'班级名'
);

再创建从表:

create table stu (
id int primary key,
name varchar(30) not null comment '学生名',
class_id int,
foreign key (class_id) references myclass(id)
);

插入数据:

mysql> insert into myclass values(10, 'C++大牛班'),(20, 'java大神班');
Query OK, 2 rows affected (0.03 sec)
Records: 2 Duplicates: 0 Warnings: 0

mysql> insert into stu values(100, '张三', 10),(101, '李四',20);
Query OK, 2 rows affected (0.01 sec)
Records: 2 Duplicates: 0 Warnings: 0

在建立外键之后,从表要插入数据,这里从表stu的myclass_id和主表的id建立外键后,从表插入数据的myclass_id必须主表有才可以插入。

mysql> insert into stu values(102,'赵五',30);
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`DataBase1`.`stu`, CONSTRAINT `stu_ibfk_1` FOREIGN KEY (`class_id`) REFERENCES `myclass` (`id`))

从表的myclass_id字段可以设置为空。

mysql> insert into stu values(102,'赵五',null);
Query OK, 1 row affected (0.00 sec)

对于主表而言,要删除主表里面的数据,需要从表里面才可以删除,要删除id=10的条目,从表里面需要没有学生的myclass_id等于10。

mysql> drop from myclass where id=20;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'from myclass where id=20' at line 1

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐