【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 where
 stu4.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; 

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值