目录
四,查询(聚合函数:count,sum,max,min,avg)
create table student (
id int not null,
sn int ,
name varchar(20),
qq_mail varchar(20)
);

create table student (
id int ,
sn int unique,
name varchar(20),
qq_mail varchar(20)
);
使用unique约束,数据库自动给对应列创建索引
create table student (
id int ,
sn int ,
name varchar(20) default ' 未命名',
qq_mail varchar(20)
);
create table student (
id int primary key auto_increment,
sn int ,
name varchar(20) ,
qq_mail varchar(20)
);
1.相当于 unique+not null
2.一个表中只能有一个(分布式部署时不能保证不重复)
3.常与 auto_increment 搭配使用,可自动增加值,也支持手动分配.
手动分配后,按手动分配后新数据继续自增


生成公式=(时间戳+机房编号/主机编号+随机因子)==>计算哈希值
create table classes (
id int primary key auto_increment,
name varchar(20),
`desc` varchar(100)
);
create table students (
id int primary key auto_increment,
sn int unique,
name varchar(20),
qq_mail varchar(20),
classes_id int,
foreign key (classes_id) references classes(id)
);
父表为classes,子表为students
在子表里创建父表的伪id
1.子表存在,不能直接删父表
2.被约束的不能直接删除
拓展:逻辑删除
将数据标记为无效
create table students (
id int primary key auto_increment,
sn int unique,
name varchar(20),
sex varchar(20),
check (sex='男' or sex='女')
);
使用时不报错且自动忽略
(1).根据需求,找到“实体”
(2).梳理实体间的关系
一对一
一对多
1.学校宿舍管理系统,要求包含宿舍信息,学生信息,每日的宿舍查房记录。
create table dormitory(
id int primary key,
number varchar(20)
);
create table student(
id int primary key,
name varchar(20),
dormitory_id int,
foreign key (dormitory_id) references dormitory(id)
);
多对多
需要额外一个关联表

可以把查询的结果插到另一个表中
insert into 表1 select * from 表2 [where ];
对某某列的行进行操作
select count(列/*)from 表

注意:
count(列),若该列为null,则不计算;若该列为*,所有列为空也计算
select sum(列名) from 表名;

空值不参加运算,直接跳过
select 列名 from 表名 group by 列名;

select 列, count(*) from 表 group by 列;
产生select 所需列,尽量不要使用*,否则分组产生的数据只显示第一个出现的行
count()

avg(),max(),min()和count类似

select 列, avg(*) from 表 wher 条件 group by 列;

select 列, avg(*) from 表 group by 列 having 条件;

联合查询/多表查询=笛卡尔积+连接条件+其他条件
select * from 表1 ,表2;

select * from 表1 ,表2 where 条件;
eg:
select * from students, classer where students.id=classes.id; () 表.列

select * from 表1 join 表2 on 条件;
1.先笛卡尔积
select * from 表1,表2 ;
2.再加上连接条件(一般是对id进行去重)
select * from 表1,表2 where 表1.id=表2.id ;
3.再加上其他限制条件,留下你需要的内容
select * from 表1,表2 where 表1.id=表2.id and 条件/group by ;
4.最后改变 select 后的 * 为所需要的列
select 列1,列2/sum(列),avg(列)... from 表1,表2 where 表1.id=表2.id and 条件/group by ;
