MySQL study notes. Database integrity

Physical integrity

Entity integrity is defined with PRIMARY KEY
Example: Define the id attribute in the book table as the main code, and define the main code at the
column level

CREATE TABLE BOOK(
	ID CHAR(8) PRIMARY KEY(ID),
	AUTHOR CHAR(30),
	PRICE FLOAT
);

Table-level definition master code

CREATE TABLE BOOK(
	ID CHAR(8),
	AUTHOR CHAR(30),
	PRICE FLOAT,
	PRIMARY KEY(ID)
);

Multi-attribute master codes can only be defined at the table level

CREATE TABLE BOOK(
	ID CHAR(8),
	AUTHOR CHAR(30),
	PRICE FLOAT,
	PRIMARY KEY(ID,AUTHOR)
);

The PRIMARY KEY constraint uniquely identifies each record in the database table.
The primary key must contain a unique value.
The primary key column cannot contain NULL values.
Each table should have a primary key, and each table can only have one primary key.

Defining completeness

1. Null values ​​are not allowed.
Example: When defining a table book, the id, author and price of the defined book cannot be null.

CREATE TABLE BOOK(
	ID CHAR(8) NOT NULL,
	AUTHOR CHAR(30) NOT NULL,
	PRICE FLOAT NOT NULL
);

2. The column value is unique.
Example: create a table book and require its author to be unique

CREATE TABLE BOOK(
	ID CHAR(8) NOT NULL,
	AUTHOR CHAR(30) UNIQUE NOT NULL,
	PRICE FLOAT NOT NULL,
	PRIMARY KEY(ID)
);

3. Use the CHECK phrase to specify the conditions that the column value should meet.
Example: Only allow sex in the book table to take male or female

CREATE TABLE BOOK(
	ID CHAR(8) PRIMARY KEY,
	AUTHOR CHAR(30),
	SEX CHAR(2) CHECK(SEX IN ('男','女')),
	PRICE FLOAT
);

The price is only allowed to take the value of 1-500

CREATE TABLE BOOK(
	ID CHAR(8) PRIMARY KEY,
	AUTHOR CHAR(30),
	SEX CHAR(2),
	PRICE FLOAT CHECK (price>=1 AND price<=500)
);

Referential integrity

Referential integrity defines the foreign key in the create table with the foreign key, and uses references to indicate the main code of which table these foreign codes refer to

CREATE TABLE BOOK(
	ID CHAR(8),
	AUTHOR CHAR(30),
	SEX CHAR(2),
	PRICE FLOAT,
	PRIMARY KEY(ID,PRICE)
);
CREATE TABLE ADDRESS(
	ID CHAR(8),
	ADDRESS CHAR(3),
	PRICE FLOAT,
	FOREIGN KEY(ID) REFERENCES BOOK(ID),
	FOREIGN KEY(PRICE) REFERENCES BOOK(PRICE)
);

Referential integrity violation processing
1. NO ACTION refused to execute
2. CASCADE cascade operation

CREATE TABLE BOOK(
	ID CHAR(8),
	AUTHOR CHAR(30),
	SEX CHAR(2),
	PRICE FLOAT,
	PRIMARY KEY(ID,PRICE)
);
CREATE TABLE ADDRESS(
	ID CHAR(8),
	ADDRESS CHAR(3),
	PRICE FLOAT,
	FOREIGN KEY(ID) REFERENCES BOOK(ID)
	ON UPDATE CASCADE,
	FOREIGN KEY(PRICE) REFERENCES BOOK(PRICE)
	ON UPDATE CASCADE
);

Guess you like

Origin blog.csdn.net/qq_44862120/article/details/111089120