【Mysql】知识点复习

440 阅读3分钟

0.sql分类:

a7bea6a88b9f8ad30748d590558b7cb.jpg

1.1插入数据:

insert intovalues (xx,xx,xx)
insert into 表 (列1,列2) values (xx,xx)

1.2修改数据

updateset1 = 值,列2 =where xxx

1.3删除数据(删除行)

delete fromwhere= xxx
delete * from

1.4删除字段

alter table table_name drop column_name

1.5增加字段

alter table table_name add (column_name1 varchar(128) not null,column_name2 int null)

2.含null的算术运算结果均为null;

ifnull(a,b):如果不为空值,则返回a;为空值,返回b

3.不等于:<>;日期在用比较运算符时,也需要加单引号

4.查找空值时,用is (not) null

5.用not时,为 where not xxx > xx

6.between 60 and 90:包括60和90

7.in是or的简写:in ('','')

8.where 列 like '曾_':一个下划线表示一个字符

9.select count/sum/avg(列)不计算null;( * )计算null

10.select count/sum/avg(distinct 列名) 可先去除重复值

补.limit y offset x:表示跳过x条数据后读取前y条数据

11.运行顺序:书写顺序—select-order-limit by:from-where-group by-having-select-order by-limit

12.order by xx desc,xxx asc

13.order by xxx asc 时空值null会直接显示在开头

14.视图:储存sql语句,可直接调用。建立视图:

create view 视图名(列名1,列名2) 
as
select xx(与列名1对应,不需要一样),xxx(同上)
...

调用视图:

select 列名1,列名2
from 视图名

15.any(子查询):任意一个;all(子查询):所有

16.where子句不能使用汇总函数,即where xxx > avg(xxx)是错误的

17.标量子查询返回单一的值

18.关联子查询:分组比较,例:查询每门课程中得分大于该门课程的平均分的学生

select name,id,score
from scores as s1
where score > (
select avg(score)
from scores as s2
where s1.id = s2.id
group by id)

19.round(数值,保留小数的位数):用于四舍五入,例:round(22.56,1)=22.6;round(22.56,0)=23;round(22.56,-1)=20

20.绝对值:abs(数值);余数:mod(5,2)=1

21.字符串长度:length('jzrz')=4;lower('A')=a,upper同理;字符串拼接:concat('a','b')=ab;字符串替换:replace('aasd','sd','ee')=aaee;字符串截取:substring('asdfgw',3,4)=dfgw

22.current_date/current_time/current_timestamp:当前日期/时间/日期和时间;year(日期)/month()/day()获取年/月/日;dayname(日期)获取该日期对应星期几

23.表的加法:Union(并集);union all(保留重复)

24.交叉联结cross join:表1的每行和表2的每行合并;内联结inner join:查找出同时存在于两个表内的行

25.left join 和 right join在没有匹配行是显示空值,若要去掉空值或只留空值,可加where b.xx is (not) null

26.(mysql不支持!) full join:left join 和 right join 结合

27.查询每个学生的选课数和总成绩:

select a.学号,姓名,count(课程号) as 选课数, sum(成绩) as 总成绩
from student as a left join score as b
on a.学号 = b.学号
group by a.学号

28.查询平均成绩大于85的学生学号和平均成绩:

select a.学号,姓名,avg(成绩)
from student as a left join score as b
on a.学号 = b.学号
group by a.学号
having avg(成绩) > 85

29.查询学生的选课情况:学号,姓名,课程号,课程名称(3表)

select a.学号,a.姓名,b.课程号,c.课程名称
from student as a inner join score as b on a.学号 = b.学号
inner join course as c on b.课程号 = c.课程号

30.case 表达式:

case when xx1 then xxx1
     when xx2 then xxx2
     ...
     else xxxn
end —————— 易忘!!!

31.查询每门课程的及格人数和不及格人数:

select 课程号,
sum(case when 成绩>=60 then 1
else 0
end) as 及格人数,
sum(case when 成绩>=60 then 0
else 1
end) as 不及格人数
from score
group by 课程号