二
9.数据抽出选项(order by,limit,offset)
order by:排序
limit:取几条数据
offset:从第几条开始取(可以实现分页)
//降序
select*from users order by score desc;
//先team升序排序,再按score降序排序
select*from users order by team,score desc;
//取前三名
select*from users order by score desc limit 3;
//取4-6名
select*from users order by score desc imit 3 offset 3;
10.统计抽出的数据(distinct,sum,max,min,group by,having)
distinct:过滤重复的数据
sum:求和
max/min:取出最大/最小值
group by/having:分组(having是针对group by的过滤条件)
//查询team
select distinct team from users;
//查询得分总和
select sum(score) from users;
//查询最高分
select max(score) from users;
//查询最低分
select min(score) from users;
//查询得分最高球员的信息
select*from users where score = (select max(score) from users);
//按队分组,并查询各个队最大得分
select team,max(score) from users group by team;
//按队分组,并查询各个队最大得分,过滤出最大得分大于25的队(排序分组之后的过滤)
select team,max(score) from users group by team having max(score) >= 25;
//按队分组,并查询各个队最大得分,过滤出最大得分大于25的队,并排序
select team,max(score) from users group by team having max(score) >= 25 order by max(score);
11.方便的函数(length,concat,alias,substring,random)
length:判断字符串长度
concat:连接2个字符串
alias:别名
substring:切割字符串
random:随机数
//查询球员名称及其长度
select player, length(player) from users;
//将球员名称和队名连接
select player, concat(player,'/',team) from users;
//设置别名
select player, concat(player,'/',team) as "球员信息" from users;
//从第一个字符开始切,切一个长度
select substring(team, 1, 1) as "球队首文字" from users;
//切割并连接
select concat('我',substring(team, 1, 1)) as "球队首文字" from users;
//获取随机数(0-1之间随机数)
select random();
//随机排序
select*from users order by random();
//随机抽选一条数据
select*from users order by random() limit 1;
12.操作多个表
//通过id关联两个表
select u.player,t.content from users as u,twitters as t where u.id = t.user_id;
//抽取单个人发言
select u.player,t.content from users as u,twitters as t where u.id = t.user_id and u.id = 1;
13.使用视图
视图:就是一个select语句(把业务系统中常用的select语句简化成一个类似于表的对象,便于简单读取和开发)
虚表,仅逻辑存在
create view:创建视图
drop view:删除视图
//不使用视图时的查询
select u.player,t.content from users as u,twitters as t where u.id = t.user_id and u.id = 1;
//创建视图
create view curry_twitters as
select u.player,t.content from users as u,twitters as t where u.id = t.user_id and u.id = 1;
//使用视图时的查询
select*from curry_twitters;
//删除视图
drop view curry_twitters;
为了提高数据查询速度,可在表中加入索引index
对于经常需要查询的语句,可以提前简历视图view,方便编码和管理
14.使用事务
事务:可以确保所有操作都成功完成,否则不会永久更新数据库。
begin:开始事务
commit:提交事务
rollback:回滚事务
//更新
begin;
update users set score = 50 where player = '库里';
update users set score = 60 where player = '哈登';
commit;
//回滚
begin;
update users set score = 0 where player = '库里';
update users set score = 0 where player = '哈登';
rollback;

浙公网安备 33010602011771号