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
UNSIGNED #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_offsetClear table distinction between
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)The above operation of deleting table records is relatively cumbersome. Logically speaking, if a department is laid off, the employees in that department will also be laid off. In fact, there is another very important content when creating a table, which is called synchronous deletion and synchronous updateNext, delete all the two newly created tables. First delete the associated table (emp), and then Delete the related table (dep)Next: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!
Explain the ACID properties (Atomicity, Consistency, Isolation, Durability).Apr 16, 2025 am 12:20 AMACID attributes include atomicity, consistency, isolation and durability, and are the cornerstone of database design. 1. Atomicity ensures that the transaction is either completely successful or completely failed. 2. Consistency ensures that the database remains consistent before and after a transaction. 3. Isolation ensures that transactions do not interfere with each other. 4. Persistence ensures that data is permanently saved after transaction submission.
MySQL: Database Management System vs. Programming LanguageApr 16, 2025 am 12:19 AMMySQL is not only a database management system (DBMS) but also closely related to programming languages. 1) As a DBMS, MySQL is used to store, organize and retrieve data, and optimizing indexes can improve query performance. 2) Combining SQL with programming languages, embedded in Python, using ORM tools such as SQLAlchemy can simplify operations. 3) Performance optimization includes indexing, querying, caching, library and table division and transaction management.
MySQL: Managing Data with SQL CommandsApr 16, 2025 am 12:19 AMMySQL uses SQL commands to manage data. 1. Basic commands include SELECT, INSERT, UPDATE and DELETE. 2. Advanced usage involves JOIN, subquery and aggregate functions. 3. Common errors include syntax, logic and performance issues. 4. Optimization tips include using indexes, avoiding SELECT* and using LIMIT.
MySQL's Purpose: Storing and Managing Data EffectivelyApr 16, 2025 am 12:16 AMMySQL is an efficient relational database management system suitable for storing and managing data. Its advantages include high-performance queries, flexible transaction processing and rich data types. In practical applications, MySQL is often used in e-commerce platforms, social networks and content management systems, but attention should be paid to performance optimization, data security and scalability.
SQL and MySQL: Understanding the RelationshipApr 16, 2025 am 12:14 AMThe relationship between SQL and MySQL is the relationship between standard languages and specific implementations. 1.SQL is a standard language used to manage and operate relational databases, allowing data addition, deletion, modification and query. 2.MySQL is a specific database management system that uses SQL as its operating language and provides efficient data storage and management.
Explain the role of InnoDB redo logs and undo logs.Apr 15, 2025 am 12:16 AMInnoDB uses redologs and undologs to ensure data consistency and reliability. 1.redologs record data page modification to ensure crash recovery and transaction persistence. 2.undologs records the original data value and supports transaction rollback and MVCC.
What are the key metrics to look for in an EXPLAIN output (type, key, rows, Extra)?Apr 15, 2025 am 12:15 AMKey metrics for EXPLAIN commands include type, key, rows, and Extra. 1) The type reflects the access type of the query. The higher the value, the higher the efficiency, such as const is better than ALL. 2) The key displays the index used, and NULL indicates no index. 3) rows estimates the number of scanned rows, affecting query performance. 4) Extra provides additional information, such as Usingfilesort prompts that it needs to be optimized.
What is the Using temporary status in EXPLAIN and how to avoid it?Apr 15, 2025 am 12:14 AMUsingtemporary indicates that the need to create temporary tables in MySQL queries, which are commonly found in ORDERBY using DISTINCT, GROUPBY, or non-indexed columns. You can avoid the occurrence of indexes and rewrite queries and improve query performance. Specifically, when Usingtemporary appears in EXPLAIN output, it means that MySQL needs to create temporary tables to handle queries. This usually occurs when: 1) deduplication or grouping when using DISTINCT or GROUPBY; 2) sort when ORDERBY contains non-index columns; 3) use complex subquery or join operations. Optimization methods include: 1) ORDERBY and GROUPB


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

SublimeText3 English version
Recommended: Win version, supports code prompts!

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment






