Mysql-学习笔记(==》约束 六)
-- 建立表的相关约束
主键约束 PRIMARY KEY (主键自带索引 PK 关系数据库领域,要求一个表只有一个主键)
CREATE TABLE t1(
tid INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
tname VARCHAR(30)
)ENGINE=MYISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
-- 复合主键 有一个重复 按另外一个排
CREATE TABLE t1(
tid INT UNSIGNED NOT NULL AUTO_INCREMENT,
tname VARCHAR(30),
PRIMARY KEY(tid,tname)
)ENGINE=MYISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
SELECT * FROM t1;
-- 主键名 CONSTRAINT myhpk
CREATE TABLE t1(
tid INT UNSIGNED NOT NULL AUTO_INCREMENT,
tname VARCHAR(30),
CONSTRAINT myhpk PRIMARY KEY(tid)
)ENGINE=MYISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
DROP TABLE t1;
存储引擎
MYISAM 速度快
INNODB 事务 外键 (联网售票,银行转账业务,对事物要求高项目)
默认约束 DEFAULT ‘男’ DEFAULT 18
CREATE TABLE t1(
tid INT UNSIGNED NOT NULL AUTO_INCREMENT,
tname VARCHAR(30) NOT NULL COMMENT '老师姓名',
tage TINYINT UNSIGNED DEFAULT 18,-- 默认年龄
PRIMARY KEY(tid)
)ENGINE=MYISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
INSERT INTO t1(tname) VALUES('李老师');
DROP TABLE t1;
CREATE TABLE t1(
tid INT UNSIGNED NOT NULL AUTO_INCREMENT,
tname VARCHAR(30) NOT NULL COMMENT '老师姓名',
tdate DATETIME DEFAULT NOW(),-- 当前时间
tage TINYINT UNSIGNED DEFAULT 18,-- 默认年龄
PRIMARY KEY(tid)
)ENGINE=MYISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
SELECT * FROM t1;
非空约束 NOT NULL
CHECK 约束(没什么卵用)
CREATE TABLE t1
(
tid INT UNSIGNED NOT NULL AUTO_INCREMENT,
tname VARCHAR(20),
tage TINYINT UNSIGNED,
CHECK (tage>18),
PRIMARY KEY(tid)
);
INSERT INTO t1 VALUES(NULL,'张三',2)
DROP TABLE t1;
外键约束 FOREIGN KEY REFERENCES 要求使用外键的表 必须是 INNODB 存储引擎
-- 根据旧表建立新表 复制结构 不复制内容
CREATE TABLE ttt LIKE student;
DROP TABLE job,s,t,student,ttt;
-- 外键的使用
CREATE TABLE teacher
(
tid INT UNSIGNED NOT NULL AUTO_INCREMENT,
tname VARCHAR(30) NOT NULL,
KEY(tname),-- 建立表的时候,同时在tname列建立索引
PRIMARY KEY(tid)
)ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
INSERT INTO teacher VALUES(NULL,'张老师'),(NULL,'李老师'),(NULL,'赵老师');
SELECT * FROM teacher;
DROP TABLE teacher;
CREATE TABLE student
(
sid INT UNSIGNED NOT NULL AUTO_INCREMENT,
sname VARCHAR(30) NOT NULL,
tid INT UNSIGNED,
PRIMARY KEY(sid),
-- constraint fk foreign key(tid) references teacher(tid) -- 建立外键 关联到teacher表
-- constraint fk foreign key(tid) references teacher(tid) on delete cascade, 删除与之关联项
CONSTRAINT fk FOREIGN KEY(tid) REFERENCES teacher(tid) ON DELETE SET NULL, -- 删除后,空的内容用null补上
)ENGINE=INNODB AUTO_INCREMENT=201601 DEFAULT CHARSET=utf8;
INSERT INTO student VALUES(NULL,'张三',1),(NULL,'赵六三',1),(NULL,'李四',2),(NULL,'王五',1)
SELECT * FROM student;