Home  >  Article  >  Database  >  What are the concepts of MySQL constraints and indexes

What are the concepts of MySQL constraints and indexes

WBOY
WBOYforward
2023-05-26 10:04:491283browse

1. Relational database design rules

Follow the ER model and the three paradigms

  • E entity represents the entity corresponding to a table in the database

  • R relationship represents the meaning of relationship

Three normal forms:

1. Columns cannot be split

2 , Unique identification

3. Relationship reference primary key

Concrete embodiment

  • Put the data into the table, and then put the table into the database.

  • There can be multiple tables in a database, and each table has a name to identify itself. Table names are unique.

  • Tables have some characteristics that define how data is stored in the table, similar to the design of "classes" in Java and Python.

  • A table consists of columns, which we also call fields. The design of the data table is actually the design and description of the meaning of each field. When creating a data table, you need to specify the data type for each field, define their data length and naming. Each field is similar to an "instance attribute" in java or python.

  • The data in the table is stored in rows, and one row is a record. Each row is similar to an "object" in java or python.

What are the concepts of MySQL constraints and indexes

2. The concepts of data integrity, constraints and indexes

1. Data integrity (Data Integrity) refers to data Accuracy and Reliability. This point aims to prevent the existence of data that does not comply with semantic regulations in the database, and at the same time avoid invalid operations or error messages caused by input and output of incorrect information.

Data The integrity should be considered from the following four aspects:

  • Entity Integrity: For example, there cannot be two identical and indistinguishable records in the same table

  • Domain Integrity: For example: age range 0-120, gender range "male/female"

  • Referential Integrity Integrity): For example: the department where the employee is located, this department must be found in the department table

  • User-defined Integrity: For example: the user name is unique, the password cannot If it is empty, etc., the salary of the manager of this department shall not be higher than 5 times the average salary of the employees in this department.

2. Constraints (CONSTRAINTS)

Constraints are used Implement and maintain data business rules and data integrity. The scope of constraints is limited to the current database. Constraints can be treated as database objects. They have names and associated patterns and are logical constraints. There will be no additional costs for setting constraints. Occupies space.

3. Index (INDEX)

The index is a separate, physical database structure stored on the data page. It is a collection and corresponding set of one or several column values ​​in the table. A list of logical pointers pointing to the physical identification data pages of the data values ​​in the table (similar to the directory index page of Xinhua Dictionary). The existence of the index will increase the storage space of the database, and will also increase the time overhead of inserting and modifying data (because When inserting and modifying data, the index will also change accordingly), but it can greatly improve the query speed. Therefore, indexes should be established on key columns or other columns that are frequently queried, sorted, and searched by range. For queries that are very Indexes should not be created on columns that are rarely used and referenced, columns that are modified very frequently, columns with few values ​​(such as gender only male and female).

What are the concepts of MySQL constraints and indexes

①Mysql Indexes will be automatically created on the primary key, unique key, and foreign key columns. If other columns need to be indexed, they need to be created manually.

②Delete the primary key and the corresponding index will also be deleted

③Delete The unique key method is achieved by deleting the corresponding index

④Delete the foreign key. The index on the foreign key column is still there. If you need to delete it, you need to delete the index separately

3. Constraints Application

1. View the constraints and indexes of a table

#查看某个表的约束
SELECT * FROM information_schema.table_constraints WHERE table_name = '表名称';
或
SHOW CREATE TABLE 表名;
#查看某个表的索引
SHOW INDEX FROM 表名称;

2. Primary key constraints: primary key

(1) The primary key is divided into single column primary key and composite primary key ( The use of composite primary keys is not recommended because composite primary keys violate the three normal forms. ):

#单个字段设置主键
create table t_user(
	id int primary key,
    username varchar(20),
    password varchar(20)
);
create table t_user(
	id int,
    username varchar(20),
    password varchar(20),
    primary key(id)
);
#多个字段设置联合主键
drop table t_user;
create table t_user(
	id int,
    username varchar(20),
    password varchar(20),
    primary key(id,username)
);
#了解
#在建表后指定主键约束
alter table 表名称 add primary key (主键字段列表);
#删除主键约束
alter table 表名称 drop primary key;

Characteristics of the primary key:

  • 1. There can only be one primary key in a table

  • 2. Set to The value of the primary key field is unique and non-null

  • 3. If the primary key consists of multiple fields, the primary key cannot be set after the field. You should use "primary key(" after all fields. Field, field)"

  • 4. In the joint primary key, each field that makes up the primary key is non-empty and can be repeated individually, but cannot be repeated at the same time

  • 5. Creating a primary key will automatically create the corresponding index, and deleting the index corresponding to the primary key will also be deleted.

3. Auto_increment constraint: auto_increment

create table t_user(
	id int primary key auto_increment,
    username varchar(20),
    password varchar(20)
);
#建表后指定自增长列
alter table [数据库.]表名 modify 自增字段名 数据类型 auto_increment;
#删除自增约束
alter table 表名 modify 自增字段名 数据类型;

Characteristics of auto-increment constraints:

Requires that only one primary key in a table be of auto-increment type Field, this field must be an integer and cannot be empty. Usually key constraints are only set on the primary key, such as primary key constraints, unique key constraints, and foreign key constraints

2、设置为自增的字段,从1开始自增;每次添加数据,都会在该字段最大值的基础上+1

3、使字段自增的方式:

  • 如果是空或者0,则实际插入的将是自动增长后的值。

  • a> insert into t_user(username,password) values(‘admin’,‘123456’);

  • b> insert into t_user values(null,‘root’,‘123456’); (推荐使用)

  • c> insert into t_user values(0,‘root’,‘123456’);

4、唯一键约束:unique key

create table t_user(
	id int primary key auto_increment,
    username varchar(20) unique key,
    password varchar(20) unique key
);
create table t_user(
	id int primary key auto_increment,
    username varchar(20),
    password varchar(20),
    unique key(username,password)
);
#在建表后增加唯一键约束
alter table 表名称 add 【constraint 约束名】 unique key (字段名列表);
#如果没有指定约束名,(字段名列表)中只有一个字段的,默认是该字段名,如果是多个字段的默认是字段名列表的第1个字段名。也可以通过show index from 表名;来查看
#删除唯一键约束
ALTER TABLE 表名称 DROP INDEX 唯一性约束名;
#注意:如果忘记名称,可以通过“show index from 表名称;”查看

唯一键约束的特点:

  • 1、设置唯一键约束的字段值唯一,但是可以为null

  • 2、一张表可以设置多个唯一键约束,也可以设置联合唯一键,即多个字段设置一个唯一约束,但是不能使用"unique key"写在字段后设置,必须写在所有字段后,使用"unique key(字段,字段)"

  • 3、联合唯一键要求组成唯一约束的字段可以单独重复,不能同时重复

  • 4、 MySQL会给唯一约束的列上默认创建一个唯一索引。

  • 5、删除唯一键只能通过删除对应索引的方式删除,删除时需要指定唯一键索引名

5、非空约束:not null

create table t_user(
	id int primary key auto_increment,
    username varchar(20) unique key not null,
    password varchar(20)
);
#在建表后指定某个字段非空
ALTER TABLE 表名称 MODIFY 字段名 数据类型 NOT NULL 【default 默认值】;
#如果该字段原来设置了默认值约束,要跟着一起再写一遍,否则默认值约束会丢失
#取消某个字段非空
ALTER TABLE 表名称 MODIFY 字段名 数据类型 【default 默认值】;
#如果该字段原来设置了默认值约束,要跟着一起再写一遍,否则默认值约束会丢失

非空约束的特点:

设置为非空约束的字段的值不能为null

6、默认值约束:default

create table t_user(
	id int primary key auto_increment,
    username varchar(20) unique key not null,
    password varchar(20),
    gender char not null default '男'
);

添加数据时使用默认值的方式:

不为该字段赋值或使用关键字default

  • insert into t_user(username,password) values(‘root’,‘123’);

  • insert into t_user values(null,‘admin123’,‘123’,default);

  • insert into t_user values(null,‘admin’,‘123’,null); //此方式不可以,会为该字段赋值为null

7、外键约束:foreign key

表关系:

1、一对一

2、多对一,在多的一方引用一的主键

  • student(sid,sname,age,sex,cid)–clazz(cid,cname,location)

3、一对多,在多的一方引用一的主键

  • clazz(cid,cname,location)–student(sid,sname,age,sex,cid)

4、多对多

  • user(uid,username,password)

  • order(oid,create_time,total_count,total_amount,status,user_id)

  • order_goods(id,oid,gid)

  • goods(gid,gname,price,sales,stock)

create table t_dept(
	id int primary key auto_increment,
    name varchar(20)
);
create table t_emp(
	id int primary key auto_increment,
    name varchar(20),
    age int,
    gender char,
    dept_id int,
    foreign key(dept_id) references t_dept(id) 
    #外键只能在所有字段列表后面单独指定
);
#在建表后指定外键约束
alter table 从表名称 add 【constraint 外键约束名】 foreign key (从表字段名) references 主表名(主表被参照字段名) 【on update xx】[on delete xx];
#删除外键约束
ALTER TABLE 表名称 DROP FOREIGN KEY 外键约束名;
#查看某个表的约束名
SELECT * FROM information_schema.table_constraints WHERE table_name = '表名称';
或
SHOW CREATE TABLE 表名;
#删除外键约束不会删除对应的索引,如果需要删除索引,需要用ALTER TABLE 表名称 DROP INDEX 索引名;
#查看索引名 show index from 表名称;

(1)外键特点

  • 外键约束是保证一个或两个表之间的参照完整性,外键是构建于一个表的两个字段或是两个表的两个字段之间的参照关系。

  • 在创建外键约束时,如果不给外键约束名称,默认名不是列名,而是自动产生一个外键名(例如 student_ibfk_1;),也可以指定外键约束名。

  • 当创建外键约束时,系统默认会在所在的列上建立对应的普通索引。但是索引名是列名,不是外键的约束名。

  • 删除外键时,关于外键列上的普通索引需要单独删除。

(2)要求

  • 在从表上建立外键,而且主表要先存在。

  • 一个表可以建立多个外键约束

  • 从表的外键列,在主表中引用的只能是键列(主键,唯一键,外键),推荐引用主表的主键。

  • 从表的外键列与主表被参照的列名字可以不相同,但是数据类型必须一样

(3)约束关系:约束是针对双方的

  • 添加了外键约束后,主表的修改和删除数据受约束

  • 添加了外键约束后,从表的添加和修改数据受约束

  • 在从表上建立外键,要求主表必须存在

  • 删除主表时,要求从表先删除,或将从表中外键引用该主表的关系先删除

(4)5个约束等级

  • Cascade方式:在父表上update/delete记录时,同步update/delete掉子表的匹配记录

  • Set null方式:在父表上update/delete记录时,将子表上匹配记录的列设为null,但是要注意子表的外键列不能为not null

  • No action方式:如果子表中有匹配的记录,则不允许对父表对应候选键进行update/delete操作

  • Restrict方式:同no action, 都是立即检查外键约束

  • Set default方式(在可视化工具SQLyog中可能显示空白):父表有变更时,子表将外键列设置成一个默认的值,但Innodb不能识别

如果没有指定等级,就相当于Restrict方式

8、检查约束:check

检查约束,mysql暂不支持

create table stu(
	sid int primary key,
	sname varchar(20),
	gender char check ('男'or'女')
);
insert into stu values(1,'张三','男');
insert into stu values(2,'李四','妖');
使用枚举类型解决如上问题:
create table stu(
	sid int primary key,
	sname varchar(20),
	gender enum ('男','女')
);

The above is the detailed content of What are the concepts of MySQL constraints and indexes. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete