其他分享
首页 > 其他分享> > mysq约束

mysq约束

作者:互联网

mysql约束

概念:对表的数据进行限定,保证数据的准确性和有效性及完整性

约束的分类

1.主键约束 primary key

2.非空约束 not null

3.唯一约束 unique

4.外键约束 foreign key

5.默认约束 default

6.检查约束 check

约束的测试

-- 测试主键及非空约束 
DROP table student;
CREATE table student(
	sid int PRIMARY KEY auto_increment,-- PRIMARY KEY auto_increment 主键自增
	sname VARCHAR(20) not null

);

INSERT INTO student (sname) VALUES ('1'); -- 成功
INSERT INTO student (sname) VALUES ('');-- 成功
INSERT INTO student (sname) VALUES (NULL);-- 失败,不能为空
SELECT * FROM student;

-- 测试默认约束 
DROP table student;
CREATE table student(
	sid int PRIMARY KEY auto_increment,-- PRIMARY KEY auto_increment 主键自增
	score double(4,1) default score=0

);
-- 测试唯一约束
drop table student;
CREATE table student(
sid int PRIMARY key auto_increment,
sname VARCHAR(20),
sfz CHAR(18) UNIQUE 

)
INSERT into student (sname,sfz) VALUES('1','1111111');
SELECT * FROM student;
INSERT into student (sname,sfz) VALUES('劳保','1111111'); -- 插入失败 UNIQUE  唯一约束,但可以为空


-- 检查约束  在mysql中无效果
DROP table student ;
CREATE TABLE student(
sid int PRIMARY key auto_increment,
sname VARCHAR(20) NOT null,
sage int CHECK (sage>20 and sage<23)

);

INSERT into student (sname,sage)VALUES('1',22);
INSERT into student (sname,sage)VALUES('老保',24);
SELECT * FROM student;

-- 外键约束

CREATE TABLE teacher(
tid int PRIMARY key auto_increment,
tname char(20),
sid int REFERENCES student.sid


);
INSERT INTO teacher (tname,sid) VALUES ('教师1',1);
INSERT INTO teacher (tname,sid) VALUES ('教师2',999);

SELECT tname FROM teacher,student WHERE teacher.sid=student.sid AND sage>20;
DROP TABLE teacher;
CREATE table teacher(
tid int PRIMARY key auto_increment,
tname CHAR(8)

);

标签:sname,increment,--,mysq,约束,student,table
来源: https://blog.csdn.net/yang_zhong_rong/article/details/116403789