sql必知必会
https://www.nowcoder.com/exam/oj/ta?page=1&tpId=298&type=298
检索数据
1.查找某些字段数据
select name,age from student
2.查找所有数据
select * from student
3.查找去重数据
select distinct(name), age from student.
4.优化事项
尽量不能使用select * .
1)select * 会浪费过多的数据库资源 ,比如cpu或者是内存。
2)多出来的数据通过io传输,会增加时间消耗
3)用不了覆盖索引会出现很多回表操作,影响查询效率。
排序检索数据
1.默认升序,降序用desc,用order by关键字
select name,age from student order by age,name desc
过滤数据与模糊查询
1.过滤数据用where
select name,age from student where age > 10
2.模糊查询
select name from student where name like ‘%花花%’
常用通配符 % 任意字符出现任意次数
_匹配一个字符
3.常用优化
1.通常筛选条件要建索引
2.在查询业务较多的表中,尽量用主键索引,因为普通索引多一个回表过程。但是在更新业务较多的场景,业务确保键值唯一的情况下,尽量建普通索引,因为普通索引可以用change buffer优化,减少随机访问磁盘的操作。
3.覆盖索引也可以不用回表,可以采用覆盖索引优化查询。
4.索引搜索满足最左前缀原则,当字段较大时,可以截取字符串前段作为索引,但是这样覆盖索引就失效了。
sql中常用函数
- sum() 求和, count() 统计个数 ,max()最大值, min()最小值
- substring(字段,start,len) 注意start开始位置从1开始
- concat(str1,str2)连接连个字符串
- upper() lower() 大小写
聚合操作
1.group by分组完以后,需要对分组数据进行筛选的,group by后面用 having
2. having 后一般会出现 函数操作
3. 分组字段一定要出现在 select 中,否则报错。
4. where ->group by->having->order by
5.常见优化
子查询,联表以及连表
1.select * from order
where user_id in (select id from user where status=1)
注意 in 后面的表驱动前表
2.select * from order
where exists (select 1 from user where order.user_id = user.id and status=1)
注意 前表驱动后面
3.内连接 join ,left join,right join 常用的这三种
join 取两表交集
left join 两表交集以及左表剩余数据
right join 两表交易以及右边剩余数据
4. union 将两个表数据连接起来
select prod_id,quantity from OrderItems where prod_id like ‘BNBG%’
union
select prod_id,quantity from OrderItems where quantity = 100
order by
prod_id
5.常见优化
- 尽量使用 union all 而不是 union ,因为union有去重操作,去重需要排序,遍历,比较等操作消耗资源
- 尽量不用子查询,用join。子查询会建临时表,然后再删除,消耗资源
3)join连表不宜过多,如果太多,可以增加冗余字段处理,主要要用小表驱动大表。
left join用左边的表驱动右边的表,join会默认用小表驱动大表。