【MySQL】数据库约束和聚合函数的使用
目录
上篇在这里喔~
1.数据库约束
1.NULL约束
2.UNIQUE唯一约束
3.DEFAULT默认值约束
4.PRIMARY KEY主键约束
5.FOREIGN KEY外键约束
2.表的设计
1.设计思路编辑
2.固定套路编辑
2.1一对一关系
2.2一对多关系
编辑
2.3多对多关系
编辑编辑编辑
3.插入查询结果
4.聚合查询
1.统计成绩共有多少
2.求小锦鲤的总成绩
3.求小锦鲤成绩的平均值
4.返回Java最高分和c++最低分
上篇在这里喔~
增删改查
1.数据库约束
1.NULL约束
create table stu1(id bigint not null);
2.UNIQUE唯一约束
3.DEFAULT默认值约束
create table stu1(id bigint not null unique,name varchar(255) default'无名氏');
4.PRIMARY KEY主键约束
create table stu1(id bigint primary key auto_increment,name varchar(255) default'无名氏');insert into stu1(id) values(1);
insert into stu1() values();
insert into stu1(id) values(8);
insert into stu1(name) values('w');
5.FOREIGN KEY外键约束
create table class(id bigint primary key auto_increment,name varchar(255) not null nuique);
create table stu2(id bigint primary key auto_increment,name varchar default '无名氏',class_id bigint,foreign key (class_id) references class(id));
delete from stu2 where class_id is not null;
select * from stu2;
delete from class where id in (1,2);
select * from class;
此时可成功删除
2.表的设计
1.设计思路
2.固定套路

2.1一对一关系
2.2一对多关系
2.3多对多关系
create table stu4(id bigint primary key auto_increment,name varchar(255) not null);
create table course(id bigint primary key auto_increment,name varchar(255) not null unique);
create table score(id bigint primary key auto_increment,score decimal(3),student_id bigint,course_id bigint,foreign key (student_id) references stu4(id),foreign key (course_id) references course(id));
3.插入查询结果
insert into stu1 values('小金');
insert into stu2(id,name) select id,name from stu1;
select * from stu1;
select * from stu2;
4.聚合查询
1.统计成绩共有多少
select count(score) from score;
select count(*) from score;
2.求小锦鲤的总成绩
select sum(score) '小锦鲤总分' from score, stu4 wherestu4.id = score.student_id and stu4.name = '小锦鲤';
3.求小锦鲤成绩的平均值
select avg(score) '平均分' from score, stu4 where
stu4.id = score.student_id and stu4.name = '小锦鲤';
4.返回Java最高分和c++最低分
select max(score) 'java最高分', min(score) 'c++最低分' from score, course
where score.course_id = course.id;