数据库的建表

时间:2021-10-11 08:17:09

第一范式:属性不可拆分

第二范式:非主键不能部分依赖组合主键

第三范式:不允许传递依赖

查询:

select * from student order by Snum desc;#按照序号降序排列
select * from student order by Sage asc;#按照年龄升序排列
select * from sc order by Snum,score desc ;#先按照序号升序排列(默认升序),再按照成绩降序排列

select * from student limit 3;#显示前3行

select * from student limit 2,3;#偏移2行再显示3行,即从第3行开始显示

select distinct Snum from sc ;#去重

聚合函数:

select count(*) from student;

max(),min(),avg(),#平均值

时间函数:

select datediff(now(),'1998-12-20');  #第一个参数减去第二个参数,返回出生了多少天

判断是否为空:第一个参数为null 则返回第二个;否则返回本身;0不是空

select ifnull(null,4) ;#结果为4
select ifnull(0,4);#结果为0 

分组函数:其中条件语句用having,where只能用在表名后面

select snum,sum(score) from sc group by snum order by sum(score) desc; #每个人的总成绩
select snum,sum(score) from sc group by snum having sum(score)>200;#总成绩大于200

起别名:1.空格  2.as 

运行顺序:from-> where->group by -> 显示(别名)->having ->order

select snum,sum(score) aa from sc where snum != 1 group by snum having aa > 200 order by sum(score) desc;

 

多表查询:

#笛卡尔积:
select * from student,sc where student.Snum = sc.snum;

关键字inner left right 要与表名相邻
#内联:
select * from student
inner join sc on student.Snum = sc.snum;

#外联

#左联:
select * from student
left join sc on student.Snum = sc.snum;

#右联:
select * from student
right join sc on student.Snum = sc.snum;

select嵌套:

select *,
(select score from sc where cnum = '01' and student.snum = sc.snum) sc01,
(select score from sc where cnum = '02' and student.snum = sc.snum) sc02
from student;  #将sc表中的课程01,02加入表student

select * from
(
select *,
(select score from sc where cnum = '01' and student.snum = sc.snum) sc01,
(select score from sc where cnum = '02' and student.snum = sc.snum) sc02
from student
) a where sc01> sc02;#显示成绩sc01>sc02的人信息

select * from
(select *,
( select score from sc where cnum = '01' and sc.snum = student.snum) sc01,
ifnull(( select score from sc where cnum = '02' and sc.snum = student.snum),0) sc02
from student ) a
where sc01 > ifnull(sc02,-1)