zl程序教程

您现在的位置是:首页 >  数据库

当前栏目

MySQL表的约束

2023-04-18 13:10:07 时间

表的约束

真正约束字段的是数据类型,但是数据类型约束很单一,需要有一些额外的约束,更好的保证数据的合法性,从业务逻辑角度保证数据的正确性。比如说我们的居民身份证,电话号码,都被要求是唯一的,这就需要约束。

空属性

空属性约束字段:null(默认)和 not null(不为空)
数据库默认字段基本都是字段为空,但是实际开发时,尽可能保证字段不为空,因为数据为空没办法参与运算。

mysql> select NULL;
+------+
| NULL |
+------+
| NULL |
+------+
1 row in set (0.00 sec)

mysql> select NULL+1;
+--------+
| NULL+1 |
+--------+
|   NULL |
+--------+
1 row in set (0.01 sec)

MySQL中的NULL不同于C语言的NULL,C语言中的NULL表示ASCII表中的0,而MySQL中的NULL表示空,不参与任何运算。

案例:
创建一个班级表,包含班级名和班级所在的教室。

站在正常的业务逻辑中:

  • 班级的名字不能为空,每个人都有对应的班级名
  • 教室的名字不能为空,每节课都有对应的教室

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

mysql> create table class (
    -> class_name varchar(20) not null,
    -> class_room varchar(20) not null
    -> )engine=innodb default charset=utf8;
Query OK, 0 rows affected (0.03 sec)

mysql> desc class;
+------------+-------------+------+-----+---------+-------+
| Field      | Type        | Null | Key | Default | Extra |
+------------+-------------+------+-----+---------+-------+
| class_name | varchar(20) | NO   |     | NULL    |       |
| class_room | varchar(20) | NO   |     | NULL    |       |
+------------+-------------+------+-----+---------+-------+
2 rows in set (0.00 sec)

插入数据时,如果没有给班级名或教室名,MySQL就会报错:

mysql> insert into class (class_name) values ('20计算机');
ERROR 1364 (HY000): Field 'class_room' doesn't have a default value

默认值

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

案例:

mysql> create table persons (
    -> name varchar(20) not null,
    -> age tinyint default 18,
    -> sex char(2) default '男'
    -> )engine=innodb default charset=utf8;
Query OK, 0 rows affected (0.02 sec)

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

mysql> insert into persons (name) values ('Curry');
Query OK, 1 row affected (0.01 sec)

mysql> select * from persons;
+-------+------+------+
| name  | age  | sex  |
+-------+------+------+
| Curry |   18 ||
+-------+------+------+
1 row in set (0.00 sec)

只有在该字段定义了默认值后,在插入的时候,才可以进行列省略。


列描述

列描述:comment,没有实际含义,专门用来描述字段,会根据表创建语句保存。

mysql> create table people (
    -> name varchar(20) not null comment '姓名',
    -> age tinyint default 18 comment '年龄',
    -> sex char(2) default '男' comment '性别'
    -> )engine=innodb default charset=utf8;
Query OK, 0 rows affected (0.01 sec)

通过desc people查看不到注释:

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

通过show create table people可以查看:

mysql> show create table people G
*************************** 1. row ***************************
       Table: people
Create Table: CREATE TABLE `people` (
  `name` varchar(20) NOT NULL COMMENT '姓名',
  `age` tinyint(4) DEFAULT '18' COMMENT '年龄',
  `sex` char(2) DEFAULT '男' COMMENT '性别'
) ENGINE=InnoDB DEFAULT CHARSET=utf8
1 row in set (0.00 sec)

zerofill

数据类型中,整型数据后的长度代表的意义与zerofill紧密相关

mysql> show create table people G
*************************** 1. row ***************************
       Table: people
Create Table: CREATE TABLE `people` (
  `name` varchar(20) NOT NULL COMMENT '姓名',
  `age` int(10) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8
1 row in set (0.00 sec)

案例:

mysql> create table table1 ( a int(10) zerofill, b int(10) )engine=innodb default charset=utf8;
Query OK, 0 rows affected (0.02 sec)

mysql> desc table1;
+-------+---------------------------+------+-----+---------+-------+
| Field | Type                      | Null | Key | Default | Extra |
+-------+---------------------------+------+-----+---------+-------+
| a     | int(10) unsigned zerofill | YES  |     | NULL    |       |
| b     | int(10)                   | YES  |     | NULL    |       |
+-------+---------------------------+------+-----+---------+-------+
2 rows in set (0.00 sec)

mysql> insert into table1 (a,b) values (10, 10);
Query OK, 1 row affected (0.01 sec)

mysql> select * from table1;
+------------+------+
| a          | b    |
+------------+------+
| 0000000010 |   10 |
+------------+------+
1 row in set (0.00 sec)

zerofill属性的作用是如果宽度小于设定的宽度,自动填充0。要注意的是,这只是最后显示的结果,在MySQL中实际存储的还是1。


主键

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

案例:

mysql> create table students (
    -> id int unsigned primary key,
    -> name varchar(10) not null
    -> )engine=innodb default charset=utf8;
Query OK, 0 rows affected (0.01 sec)

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

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

mysql> insert into students (id,name) values (1, 'Durant');
Query OK, 1 row affected (0.00 sec)

mysql> insert into students (id,name) values (1, 'Curry');
ERROR 1062 (23000): Duplicate entry '1' for key 'PRIMARY'

删除主键:

alter table 表名 drop primary key

示例:

mysql> alter table students drop primary key;
Query OK, 1 row affected (0.04 sec)
Records: 1  Duplicates: 0  Warnings: 0

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

当表创建好以后但是没有主键的时候,可以再次追加主键:

alter table 表名 add primary key (字段列表)

示例:

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

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

复合主键:在创建表的时候,在所有字段之后,使用primary key(主键字段列表)来创建主键,如果有多个字段作为主键,可以使用复合主键。

案例:

mysql> create table students (
    -> id int unsigned,
    -> course char(10) comment '课程代码',
    -> score tinyint unsigned comment '分数',
    -> primary key(id, course)
    -> )engine=innodb default charset=utf8;
Query OK, 0 rows affected (0.02 sec)

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

mysql> insert into students (id,course) values (1, '123');
Query OK, 1 row affected (0.00 sec)

mysql> insert into students (id,course) values (1, '124');
Query OK, 1 row affected (0.00 sec)

mysql> insert into students (id,course) values (1, '123');
ERROR 1062 (23000): Duplicate entry '1-123' for key 'PRIMARY'


自增长

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

自增长的特点:

  • 任何一个字段要做自增长,前提是本身是一个索引(key一栏有值)
  • 自增长字段必须是整数
    -一张表最多只能有一个自增长
mysql> create table persons (
    -> id int unsigned primary key auto_increment,
    -> name varchar(10) not null
    -> )engine=innodb default charset=utf8;
Query OK, 0 rows affected (0.02 sec)

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

mysql> insert into persons (name) values ('a');
Query OK, 1 row affected (0.00 sec)

mysql> insert into persons (name) values ('b');
Query OK, 1 row affected (0.00 sec)

mysql> select * from persons;
+----+------+
| id | name |
+----+------+
|  1 | a    |
|  2 | b    |
+----+------+
2 rows in set (0.00 sec)

唯一键

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

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

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

比如说,有一张存放公民信息的表,里面字段有身份证号,姓名,性别,手机号和家庭住址,我们可以使用身份证号作为主键,因为身份证号码具有唯一性,但是由于数据库是具有很强的数据明确性的,不允许有本应该唯一的字段被误操作添加重复的值,所以数据库就需要一种约束,约束公民的其他唯一存在的字段比如手机号不能重复,这个约束就叫做唯一键。

案例:

mysql> create table person (
    -> id int unsigned primary key,
    -> telephone int unsigned unique not null,
    -> sex char(2) default '男',
    -> address varchar(20) not null
    -> )engine=innodb default charset=utf8;
Query OK, 0 rows affected (0.03 sec)

mysql> desc person;
+-----------+------------------+------+-----+---------+-------+
| Field     | Type             | Null | Key | Default | Extra |
+-----------+------------------+------+-----+---------+-------+
| id        | int(10) unsigned | NO   | PRI | NULL    |       |
| telephone | int(10) unsigned | NO   | UNI | NULL    |       |
| sex       | char(2)          | YES  |     ||       |
| address   | varchar(20)      | NO   |     | NULL    |       |
+-----------+------------------+------+-----+---------+-------+
4 rows in set (0.00 sec)

mysql> insert into person (id, telephone, sex, address) values(3306, 8520170, '男', '福建漳州');
Query OK, 1 row affected (0.00 sec)

mysql> insert into person (id, telephone, sex, address) values(8080, 8520170, '男', '福建漳州');
ERROR 1062 (23000): Duplicate entry '8520170' for key 'telephone'

外键

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

对比外键和外键约束:

  • 外键是在逻辑上关联两个表的字段,但是仅仅在逻辑上有关联是不够的,需要有MySQL的操作来维护两个表逻辑的正确性
  • 外键约束就是MySQL用来约束两个表逻辑关系正确性的约束

案例:

创建主表:

mysql> create table Class (
    -> id int primary key,
    -> class_name varchar(20) not null
    -> )engine=innodb default charset=utf8;
Query OK, 0 rows affected (0.02 sec)

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

创建从表:

mysql> create table Stu (
    -> id int primary key,
    -> name varchar(20) not null,
    -> class_id int,
    -> foreign key (class_id) references Class(id)
    -> )engine=innodb default charset=utf8;
Query OK, 0 rows affected (0.03 sec)

mysql> desc Stu;
+----------+-------------+------+-----+---------+-------+
| Field    | Type        | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+-------+
| id       | int(11)     | NO   | PRI | NULL    |       |
| name     | varchar(20) | NO   |     | NULL    |       |
| class_id | int(11)     | YES  | MUL | NULL    |       |
+----------+-------------+------+-----+---------+-------+
3 rows in set (0.00 sec)

插入数据:如果插入不存在的班级,就会报错

mysql> insert into Stu (id, name, class_id) values (30, 'Curry', 10);
Query OK, 1 row affected (0.00 sec)

mysql> insert into Stu (id, name, class_id) values (35, 'Durant', 20);
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`table_restraint`.`Stu`, CONSTRAINT `Stu_ibfk_1` FOREIGN KEY (`class_id`) REFERENCES `Class` (`id`))