默认值约束
1 CREATE TABLE USER( 2 uid INT, 3 uname VARCHAR(10), 4 address VARCHAR(30) DEFAULT '山东省' 5 ) 6 DROP TABLE USER; 7 SELECT * FROM USER; 8 INSERT INTO USER(uid,uname) VALUES(1,'张三'); 9 INSERT INTO USER VALUES(2,'李四','河南省'); 10 INSERT INTO USER VALUES(3,'李四',NULL);
非空约束
1 CREATE TABLE USER( 2 uid INT NOT NULL, 3 uname VARCHAR(10), 4 address VARCHAR(30) DEFAULT '山东省' 5 ) 6 INSERT INTO USER(uid,uname) VALUES(1,'张三');
唯一约束
1 CREATE TABLE USER( 2 uid INT UNIQUE, 3 uname VARCHAR(10), 4 address VARCHAR(30) DEFAULT '山东省' 5 ) 6 INSERT INTO USER(uid,uname) VALUES(1,'张三'); 7 INSERT INTO USER(uid,uname) VALUES(2,'张三');
主键约束(唯一+非空)
1)被约束的表称为副表,约束别人的表称为主表,外键设置在副表上的!!!
2)主表的参考字段通用为主键!
3)添加数据: 先添加主表,再添加副表
4)修改数据: 先修改副表,再修改主表
5)删除数据: 先删除副表,再删除主表
一个表内只能有一个主键。
1 CREATE TABLE USER( 2 uid INT PRIMARY KEY, 3 uname VARCHAR(10), 4 address VARCHAR(30) DEFAULT '山东省' 5 ) 6 SELECT * FROM USER; 7 INSERT INTO USER(uid,uname) VALUES(1,'张三');
自增长约束AUTO_INCREMENT
1 CREATE TABLE USER( 2 uid INT PRIMARY KEY AUTO_INCREMENT, 3 uname VARCHAR(10), 4 address VARCHAR(30) DEFAULT '山东省' 5 ) 6 INSERT INTO USER(uname) VALUES('张三');
零填充
1 CREATE TABLE USER( 2 uid INT(3) ZEROFILL PRIMARY KEY AUTO_INCREMENT, 3 uname VARCHAR(10), 4 address VARCHAR(30) DEFAULT '山东省' 5 ) 6 INSERT INTO USER(uname) VALUES('张三');
delete from 清空表不能删除约束
1 DELETE FROM USER;
TRUNCATE TABLE 清空表可以删除约束
1 TRUNCATE TABLE USER;
外键约束(约束两种表的数据)
1 CREATE TABLE dept( 2 deptid INT PRIMARY KEY AUTO_INCREMENT, 3 deptname VARCHAR(10) 4 ) 5 INSERT INTO dept(deptname) VALUES('软件开发部'); 6 INSERT INTO dept(deptname) VALUES('软件测试部'); 7 INSERT INTO dept(deptname) VALUES('软件运维部'); 8 SELECT * FROM dept; 9 CREATE TABLE empt( 10 eid INT PRIMARY KEY AUTO_INCREMENT, 11 ename VARCHAR(5), 12 deptid INT, 13 CONSTRAINT dept_empt_fk FOREIGN KEY(deptid) REFERENCES dept(deptid) 14 )
新增副表
1 INSERT INTO empt(ename,deptid) VALUES('张三',1); 2 SELECT * FROM empt
修改主表
1 UPDATE dept SET deptname=2 WHERE deptid=1; 2 UPDATE empt SET deptid=3 WHERE eid=1;
删除主表
1 DELETE FROM dept WHERE deptid=2;