MySQL database: data integrity and application constraints

Data integrity

1. Domain integrity: --------- integrity Match: non-empty, the default
field / column

2. Entity integrity: ------- integrity Match: primary key, unique key
record / row

3. referential integrity: foreign keys: ------- matching integrity
between the table and the table

Constraint: constraint

Bound Categories in MySQL

Primary key: primary key
unique key: unique
non-empty: not null
default: default
Foreign key: foreign key

Primary keys, unique keys, foreign keys are automatically created indexes
primary key: a table can have only one primary key, which may correspond to a field, may also correspond to a plurality of fields (composite primary key)
unique key: also a candidate for the primary key (difference with a primary key that may store a null value)
foreign key: primary or unique key from the master table (which allow for the blank, and its value must be present in the primary table too)

Creating Constraints
constraint 约束名 约束类型(字段名) references 主表(主键字段或唯一键字段)

Create a foreign key constraint

constraint 约束名 foreign key(对应字段) references 主表(主键字段或唯一键字段)

Create a composite primary key

primary key (字段1,字段2)

For tables that already exist, create a unique key constraint

alter table 表名 add constraint 约束名 unique(字段名);

Delete to delete the sub-constrained data table data, and then delete the main table data

Cascading delete

on delete cascade 

Cascading update

on update cascade

Turn off foreign key constraint mysql

SET FOREIGN_KEY_CHECKS=0;

Open foreign key constraint mysql

SELECT  @@FOREIGN_KEY_CHECKS;

Remove the foreign key
Note: This statement can not be associated to delete the foreign key constraint is automatically generated after you remove the foreign key

alter table 表名 drop foreign key 外键名称;

The only key to delete
Note: corresponding index will be automatically deleted after the only key to delete

alter table 表名 drop index 唯一键字段名;

Delete the specified index name

alter table 表名 drop index 索引名称;

Reminder: For outer table has a primary association, the data deletion table, if not removed before the cascade operation, the master table data is deleted, must be deleted from the corresponding data table

Guess you like

Origin www.cnblogs.com/yanlzy/p/11909258.html