Touge-MySQL Development Skills (Index and Integrity)

index

definition:

An index is a correspondence table between column values ​​and record rows created in a certain order based on one or several columns in a table.
After creating an index on a column, to find data, you can directly find the position of the corresponding row based on the index on the column, so as to quickly find the data.

Classification:

  • Ordinary index (INDEX): basic index type
  • Unique index (UNIQUE): all values ​​​​of the column are not repeated
  • Primary key (PRIMARY KEY): a unique index, a table can only have one primary key
  • Full text index (FULLTEXT): can only be created on varchar or text type

Grammar format:

create

CREATE [UNIQUE|FULLTEXT|SPATIAL] INDEX 索引名称 ON 表名 { 字段名称[(长度)] [ASC|DESC]}
ALTER TABLE tbl_name ADD [UNIQUE|FULLTEXT|SPATIAL] INDEX 索引名称(字段名称[(长度)][ASC|DESC]);

view index

show index from 表名;

rename index

alter index 原索引名
	rename to 新索引名;

delete index

drop index 索引名;

data integrity

domain integrity

Domain integrity is also called column integrity, which mainly constrains a column of data. For example, the value of sex in emp can only be one of 1 and 2. You can define sex as follows when creating a table:

sex int(1) check(sex='1' or sex='2')NOT NULL,

Or add a sentence after all field definitions are complete:

constraint ch_sex check(sex='1' or sex='2')

Create constraints by modifying the table:

alter table emp
	add(contraint ch_sex check(sex='1' or sex='2'));

Remove constraints:

alter table emp
	drop constraint ch_sex;

entity integrity

Also known as row integrity, each row is required to have a unique identifier. For example, the employee eid in emp is unique, so that a certain person can be uniquely identified. Entity integrity can be achieved through unique constraints and primary key constraints.
Similarly, when creating a table, telthe creation constraint should be teldefined as:

tel char(12) NOT NULL constraint un_tel unique,

Create constraints by modifying the table:

alter table emp
	add constraint un_tel unique (tel);

referential integrity

Also known as referential integrity, it ensures the data consistency between the master table and the slave table, and defines the foreign key and the primary key when implementing it.

  • A slave table cannot refer to a key value that does not exist in the master table
  • If the value in the main table is changed, all references in the slave table should also be modified
  • To delete a record in the main table, you should first delete the matching record from the table

defined at creation time

字段名 字段类型(字段长度) NOT NULL references 主表名(外键),

eid char(6) NOT NULL refrences sal(eid),

Define when modifying a table

alter table emp
	add constraint sal_id foreign key(eid)
		references sal(eid);

おすすめ

転載: blog.csdn.net/m0_71290816/article/details/127273410