Data constraints
Data of the user data constraints is to constrain the operation table.
1. Default: When users use the default value for the field is not inserted value time, default value is used.
1 ) the insertion of the default value field null is possible.
2 ) The default values for a field to a non- null
CREATE TABLE student(
id INT,
NAME VARCHAR(20),
address VARCHAR (20) DEFAULT ' Zibo ' - Default
)
2. Non-empty: limit field must be assigned
1 ) non-blank characters must be assigned
2 ) non-null character can not be assigned null
CREATE TABLE student(
id INT,
NAME VARCHAR(20),
gender VARCHAR (2) NOT NULL - non-empty
)
3. Unique: field values can not be repeated
1 ) The only field that can be inserted null
2 ) The only field that can be inserted into a plurality of null
CREATE TABLE student(
id INT UNIQUE, - the only
NAME VARCHAR(20)
)
4. Primary Key: unique non-null +
1 ) Typically, each table will have a primary key field. Used to uniquely mark each record in the table.
2 ) recommended not to select field contains the business meaning of the table as the primary key, it is recommended to design a separate table for each non-business meaning of id field.
CREATE TABLE student(
id INT PRIMARY KEY, - the primary key
NAME VARCHAR(20)
)
5. Self Growth: auto-increment
CREATE TABLE student(
id INT (4) ZEROFILL PRIMARY KEY AUTO_INCREMENT, - from growth, from 0 to start ZEROFILL zero padding
NAME VARCHAR(20)
)
6. Foreign Key: two kinds of constraint data table
Two phenotypic situation appears:
Solve the problem of high data redundancy: separate out a table
For example: employee table and the department table
Problem: insert the employee table in the data, the department staff table ID field can easily insert! ! ! ! !
A foreign key constraint: constraint insert department employees table ID field value
Solution: In the department staff table ID to add a foreign key constraint field
- the department table (the primary table) CREATE TABLE dept( id INT PRIMARY KEY, deptName VARCHAR(20) )
- Modify the staff tables (side tables / Table) CREATE TABLE employee( id INT PRIMARY KEY, empName VARCHAR(20), deptId INT, - the name of the department was changed to Department ID - declare a foreign key constraint CONSTRAINT emlyee_dept_fk FOREIGN KEY(deptId) REFERENCES dept(id) - foreign key name of the foreign key reference table ( reference fields ) ) |
note:
1 ) is constrained tables as sub-tables, constraints others tables as the primary table, foreign keys arranged in the sub-table! ! !
2 ) primary table primary key common reference field!
3 ) Adding data: first add the main table, and then add the sub-table
4 ) modify the data: the first modification sub-table, and then modify the main table
5 ) delete the data: first remove the side tables, and then delete the main table