First, the six constraints
- NOT NULL non-empty
- PRIMARY KEY primary key
- UNIQUE unique
- CHECK check constraint, MySQL does not support, syntax error but there was no effect
- FOREIGN KEY foreign key. Two limit table relationships, introduced from the normal value table foreign key constraints, the introduction of the value of a column in the primary table, to ensure that the value of this field must be derived from the primary table associated with the table in the column
- DEFAULT default value / setpoint system
Second, the table level and column-level constraint definition:
-
Table-level constraints: constraints on the establishment of multiple data columns, called table-level constraints can only table-level constraints after the column definition statement
-
Column-level constraints: constraints on the establishment of a data column, called a column-level constraint column-level constraints may be declared in the column definition, can also be a statement after the column definition
Third, the timing of adding constraints:
- When you create a table:
# Create the main table, the foreign key experiment
CREAT TABLE IF NOT EXISTS major(
id INT,
major_name varchar(20)
);
# Created from a table, table-level experiment / column-level constraint
CREAT TABLE IF NOT EXISTS students(
# Add a table-level constraints, can be added directly after the type
id INT PRIMARY KEY,
student_name VARCHAR(20),
sex CHAR(1),
age INT DEFAULT 18,
majorid INT,
# Add a table-level constraints, added directly after the end of the column is created
CONSTRAINT pk PRIMARY KEY (id). # Primary key, used to name the constraint, may be applied without
CONSTRAINT fk_student_majory FOREIGN KEY(majorid) REFERENCES major(id)#外键
);
- When modify the table:
# Add a non-empty, the other column-level constraints can follow this method
ALTER TABLE students MODIFY COLUMN student_name VARCHAR(20) NOT NULL;