1. Introduction
The constraints are the same as the width of the data type and are optional parameters
Function: Used to ensure data The integrity and consistency
is mainly divided into:
PRIMARY KEY
(PK) #Identifies this field as the primary key of the table, which can be uniquely identified Record
FOREIGN KEY
(FK) #Identifies this field as the foreign key of the table
NOT NULL
#Identifies that this field cannot be empty
UNIQUE KEY
(UK) #The value that identifies this field is unique
AUTO_INCREMENT
#The value that identifies this field grows automatically (integer type, And it is the primary key)
DEFAULT
#Set the default value for this field
U
NSIGNED
#Unsigned
ZEROFILL
#Use 0 to fill
Instructions:
#1. Whether to allow empty, the default is NULL, NOT NULL can be set, the field is not allowed Is empty, must be assigned a value
#2. Whether the field has a default value, the default value is NULL, if the field is not assigned a value when inserting the record, this field uses the default value
sex enum ('male','female') not null default 'male'
#Must be a positive value (unsigned), not allowed to be empty, the default is 20age int unsigned NOT NULL default 20
# 3. Whether it is key
primary key
foreign key foreign key
index (index, unique...)
2. NOT NULL and DEFAULT
Whether it is nullable, null means empty, non-string
not null - not nullable
null - nullable
Default value, you can specify the default value when creating a column. If it is not actively set when inserting data, the default value will be automatically added
create table tb1( nid int not null defalut 2, num int not null);
Note:
1. Default The value can be empty
2. Set not null, and it cannot be empty when inserting the value
3. After setting the id field to have a default value, it will work regardless of whether the id field is null or not null. Insert a blank, and the default value specified by default is filled in when inserting a blank
3. UNIQUE
Chinese translation: different. In mysql, it is called single column unique
Example: Create a company department table (each company has a unique department)
mysql> create table department( -> id int, -> name char(10) -> ); Query OK, 0 rows affected (0.01 sec) mysql> insert into department values(1,'IT'),(2,'IT'); Query OK, 2 rows affected (0.00 sec) Records: 2 Duplicates: 0 Warnings: 0mysql> select * from department; +------+------+| id | name | +------+------+| 1 | IT | | 2 | IT | +------+------+2 rows in set (0.00 sec) # 发现: 同时插入两个IT部门也是可以的,但这是不合理的,所以我们要设置name字段为unique 解决这种不合理的现象。
Next, use the constraint unique to define the company department fields to set.
#第一种创建unique的方式#例子1:create table department( id int, name char(10) unique ); mysql> insert into department values(1,'it'),(2,'it'); ERROR 1062 (23000): Duplicate entry 'it' for key 'name' #例子2:create table department( id int unique, name char(10) unique ); insert into department values(1,'it'),(2,'sale'); #第二种创建unique的方式create table department( id int, name char(10) , unique(id), unique(name) ); insert into department values(1,'it'),(2,'sale');
United uniqueness:
# 创建services表mysql> create table services( id int, ip char(15), port int, unique(id), unique(ip,port) ); Query OK, 0 rows affected (0.05 sec) mysql> desc services; +-------+----------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------+----------+------+-----+---------+-------+ | id | int(11) | YES | UNI | NULL | | ip | char(15) | YES | MUL | NULL | | port | int(11) | YES | | NULL | |+-------+----------+------+-----+---------+-------+| 3 rows in set (0.01 sec) #联合唯一,只要两列记录,有一列不同,既符合联合唯一的约束mysql> insert into services values (1,'192,168,11,23',80), (2,'192,168,11,23',81), (3,'192,168,11,25',80); Query OK, 3 rows affected (0.01 sec) Records: 3 Duplicates: 0 Warnings: 0 mysql> select * from services; +------+---------------+------+ | id | ip | port | +------+---------------+------+ | 1 | 192,168,11,23 | 80 | | 2 | 192,168,11,23 | 81 | | 3 | 192,168,11,25 | 80 | +------+---------------+------+ 3 rows in set (0.00 sec) mysql> insert into services values (4,'192,168,11,23',80); ERROR 1062 (23000): Duplicate entry '192,168,11,23-80' for key 'ip'
4. PRIMARY KEY
There is only one unique in a table in MySQL A primary key cannot have multiple columns, but it can have a composite primary key
A table can have:
Single column as the primary key
Multiple columns as the primary key (composite primary key)
Constraint: Equivalent to not null unique, the value of the field is not empty and unique
The storage engine default is (innodb): For the innodb storage engine, a table must have a primary key.
Single column primary key:
# 创建t14表,为id字段设置主键,唯一的不同的记录create table t14( id int primary key, name char(16) ); insert into t14 values(1,'xiaoma'),(2,'xiaohong'); mysql> insert into t14 values(2,'wxxx'); ERROR 1062 (23000): Duplicate entry '6' for key 'PRIMARY' # not null + unique的化学反应,相当于给id设置primary key create table t15( id int not null unique, name char(16) ); mysql> create table t15( -> id int not null unique, -> name char(16) -> ); Query OK, 0 rows affected (0.01 sec) mysql> desc t15; +-------+----------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------+----------+------+-----+---------+-------+ | id | int(11) | NO | PRI | NULL | | | name | char(16) | YES | | NULL | | +-------+----------+------+-----+---------+-------+ 2 rows in set (0.02 sec)
Composite primary key:
create table t16( ip char(15), port int, primary key(ip,port) ); insert into t16 values('1.1.1.2',80),('1.1.1.2',81);
5. AUTO_INCREMENT
Constraints: The constrained fields are automatically grown, and the constrained fields must be constrained by key at the same time
create table student( id int primary key auto_increment, name varchar(20), sex enum('male','female') default 'male' );
1. If the id is not specified, it will grow automatically
2. You can also specify the id
3. For a self-increasing field, after deleting it with delete and then inserting the value, the field will continue to grow according to the position before deletion
##auto_increment_increment and
auto_increment_offset The difference between
查看可用的 开头auto_inc的词 mysql> show variables like 'auto_inc%'; +--------------------------+-------+ | Variable_name | Value | +--------------------------+-------+ | auto_increment_increment | 1 | | auto_increment_offset | 1 | +--------------------------+-------+ rows in set (0.02 sec) # 步长auto_increment_increment,默认为1 # 起始的偏移量auto_increment_offset, 默认是1 # 设置步长 为会话设置,只在本次连接中有效 set session auto_increment_increment=5; #全局设置步长 都有效。 set global auto_increment_increment=5; # 设置起始偏移量 set global auto_increment_offset=3; #强调:If the value of auto_increment_offset is greater than that of auto_increment_increment, the value of auto_increment_offset is ignored. 翻译:如果auto_increment_offset的值大于auto_increment_increment的值,则auto_increment_offset的值会被忽略 # 设置完起始偏移量和步长之后,再次执行show variables like'auto_inc%'; 发现跟之前一样,必须先exit,再登录才有效。 mysql> show variables like'auto_inc%'; +--------------------------+-------+ | Variable_name | Value | +--------------------------+-------+ | auto_increment_increment | 5 | | auto_increment_offset | 3 | +--------------------------+-------+ rows in set (0.00 sec) #因为之前有一条记录id=1 mysql> select * from student; +----+---------+------+ | id | name | sex | +----+---------+------+ | 1 | xiaobai | male | +----+---------+------+ row in set (0.00 sec) # 下次插入的时候,从起始位置3开始,每次插入记录id+5 mysql> insert into student(name) values('ma1'),('ma2'),('ma3'); Query OK, 3 rows affected (0.00 sec) Records: 3 Duplicates: 0 Warnings: 0 mysql> select * from student; +----+---------+------+ | id | name | sex | +----+---------+------+ | 1 | xiaobai | male | | 3 | ma1 | male | | 8 | ma2 | male | | 13 | ma3 | male | +----+---------+------+ auto_increment_increment和 auto_increment_offset
delete and
truncate:
#1.创建表时先创建被关联表,再创建关联表 # 先创建被关联表(dep表) create table dep( id int primary key, name varchar(20) not null, descripe varchar(20) not null ); #再创建关联表(emp表) create table emp( id int primary key, name varchar(20) not null, age int not null, dep_id int, constraint fk_dep foreign key(dep_id) references dep(id) ); #2.插入记录时,先往被关联表中插入记录,再往关联表中插入记录 insert into dep values (1,'IT','IT技术有限部门'), (2,'销售部','销售部门'), (3,'财务部','花钱太多部门'); insert into emp values (1,'zhangsan',18,1), (2,'lisi',19,1), (3,'djb',20,2), (4,'dogfa',40,3), (5,'oldniu',18,2); 3.删除表 #按道理来说,删除了部门表中的某个部门,员工表的有关联的记录相继删除。 mysql> delete from dep where id=3; ERROR 1451 (23000): Cannot delete or update a parent row: a foreign key constraint fails (`db5`.`emp`, CONSTRAINT `fk_name` FOREIGN KEY (`dep_id`) REFERENCES `dep` (`id`)) #但是先删除员工表的记录之后,再删除当前部门就没有任何问题 mysql> delete from emp where dep =3; Query OK, 1 row affected (0.00 sec) mysql> select * from emp; +----+----------+-----+--------+ | id | name | age | dep_id | +----+----------+-----+--------+ | 1 | zhangsan | 18 | 1 | | 2 | lisi | 18 | 1 | | 3 | djb | 20 | 2 | | 5 | oldniu | 18 | 2 | +----+----------+-----+--------+ rows in set (0.00 sec) mysql> delete from dep where id=3; Query OK, 1 row affected (0.00 sec) mysql> select * from dep; +----+-----------+----------------------+ | id | name | descripe | +----+-----------+----------------------+ | 1 | IT | IT技术有限部门 | | 2 | 销售部 | 销售部门 | +----+-----------+----------------------+ rows in set (0.00 sec)
Repeat the above operation to create the table
Note: Add
on delete cascade to the related table #Synchronous deletion
on update cascade #Synchronous update
Modify emp table:
create table emp( id int primary key, name varchar(20) not null, age int not null, dep_id int, constraint fk_dep foreign key(dep_id) references dep(id) on delete cascade #同步删除 on update cascade #同步更新 );
接下来的操作,就符合我们正常的生活中的情况了。
#再去删被关联表(dep)的记录,关联表(emp)中的记录也跟着删除 mysql> delete from dep where id=3; Query OK, 1 row affected (0.00 sec) mysql> select * from dep; +----+-----------+----------------------+ | id | name | descripe | +----+-----------+----------------------+ | 1 | IT | IT技术有限部门 | | 2 | 销售部 | 销售部门 | +----+-----------+----------------------+ rows in set (0.00 sec) mysql> select * from emp; +----+----------+-----+--------+ | id | name | age | dep_id | +----+----------+-----+--------+ | 1 | zhangsan | 18 | 1 | | 2 | lisi | 19 | 1 | | 3 | djb | 20 | 2 | | 5 | oldniu | 18 | 2 | +----+----------+-----+--------+ rows in set (0.00 sec)
#再去更改被关联表(dep)的记录,关联表(emp)中的记录也跟着更改
mysql> update dep set id=222 where id=2; Query OK, 1 row affected (0.02 sec) Rows matched: 1 Changed: 1 Warnings: 0
# 赶紧去查看一下两张表是否都被删除了,是否都被更改了 mysql> select * from dep; +-----+-----------+----------------------+ | id | name | descripe | +-----+-----------+----------------------+ | 1 | IT | IT技术有限部门 | | 222 | 销售部 | 销售部门 | +-----+-----------+----------------------+ rows in set (0.00 sec) mysql> select * from emp; +----+----------+-----+--------+ | id | name | age | dep_id | +----+----------+-----+--------+ | 1 | zhangsan | 18 | 1 | | 2 | lisi | 19 | 1 | | 3 | djb | 20 | 222 | | 5 | oldniu | 18 | 222 | +----+----------+-----+--------+ rows in set (0.00 sec)
以上便是常用约束的详细实例介绍,想了解更多相关问题请访问PHP中文网:mysql视频教程
The above is the detailed content of Detailed introduction to mysql integrity constraints. For more information, please follow other related articles on the PHP Chinese website!