MySQL Others--约束(Constraint)示例
ENUM约束
--使用ENUM来限制用户输入 CREATE TABLE Student ( StudentID INT AUTO_INCREMENT PRIMARY KEY, ClassID INT, StudentName VARCHAR(200), Sex ENUM('Male','Female') )
默认值约束
--创建表时指定默认值 CREATE TABLE Student ( StudentID INT AUTO_INCREMENT PRIMARY KEY, ClassID INT, StudentName VARCHAR(200) DEFAULT '' ) --创建表后再创建默认约束 CREATE TABLE Student ( StudentID INT AUTO_INCREMENT PRIMARY KEY, ClassID INT, StudentName VARCHAR(200) ) ALTER TABLE Student ALTER COLUMN StudentName SET DEFAULT '' --查看默认约束 SHOW CREATE TABLE Student;
外键约束
MYSQL 对外键约束只支持即时检查(immediate check), 与SQL SERVER 相同。
ORACLE 对外键约束支持延时检查(deferred check)。
在创建外键约束时,MYSQL 默认为外键约束列添加索引,以避免外键约束带来的死锁问题。
--创建被引用的班级表 CREATE TABLE Class ( ClassID INT AUTO_INCREMENT PRIMARY KEY, ClassName VARCHAR(200) ); --创建学生表时外键引用班级表 CREATE TABLE Student ( StudentID INT AUTO_INCREMENT PRIMARY KEY, ClassID INT, StudentName VARCHAR(200), FOREIGN KEY(ClassID) REFERENCES Class(ClassID) ) --创建学生表,然后再增加外键 CREATE TABLE Student ( StudentID INT AUTO_INCREMENT PRIMARY KEY, ClassID INT, StudentName VARCHAR(200), ); ALTER TABLE Student ADD FOREIGN KEY(ClassID) REFERENCES Class(ClassID); --查看外键 SELECT * FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS WHERE CONSTRAINT_SCHEMA='testdb1' AND TABLE_NAME='Student' \G *************************** 1. row *************************** CONSTRAINT_CATALOG: def CONSTRAINT_SCHEMA: testdb1 CONSTRAINT_NAME: student_ibfk_1 UNIQUE_CONSTRAINT_CATALOG: def UNIQUE_CONSTRAINT_SCHEMA: testdb1 UNIQUE_CONSTRAINT_NAME: PRIMARY MATCH_OPTION: NONE UPDATE_RULE: RESTRICT DELETE_RULE: RESTRICT TABLE_NAME: student REFERENCED_TABLE_NAME: class
在数据导入过程中,为提高导入效率,可以先禁用外键检查,导入完后再开启。
--禁用外键检查
SET @@foreign_key_checks=0;
--启用外键检查
SET @@foreign_key_checks=1;
唯一约束
--创建学生表时外键引用班级表 CREATE TABLE Student ( StudentID INT AUTO_INCREMENT PRIMARY KEY, ClassID INT, StudentName VARCHAR(200), UNIQUE KEY (StudentName) ) --创建表后再增加唯一约束 CREATE TABLE Student ( StudentID INT AUTO_INCREMENT PRIMARY KEY, ClassID INT, StudentName VARCHAR(200) ) ALTER TABLE Student ADD UNIQUE KEY(StudentName); --查看约束 SELECT * FROM information_schema.TABLE_CONSTRAINTS WHERE CONSTRAINT_SCHEMA='testdb1' AND TABLE_NAME='Student' \G *************************** 1. row *************************** CONSTRAINT_CATALOG: def CONSTRAINT_SCHEMA: testdb1 CONSTRAINT_NAME: PRIMARY TABLE_SCHEMA: testdb1 TABLE_NAME: student CONSTRAINT_TYPE: PRIMARY KEY *************************** 2. row *************************** CONSTRAINT_CATALOG: def CONSTRAINT_SCHEMA: testdb1 CONSTRAINT_NAME: StudentName TABLE_SCHEMA: testdb1 TABLE_NAME: student CONSTRAINT_TYPE: UNIQUE