小心的sql打怪晋级


前言

索引

一、索引的优缺点?

1.优点:

				(1)大大加快检索数据的速度;
				(2)加速表与表之间的连接;
				(3)创建唯一索引保证表内数据每一行的唯一性;
				(4)在用分组group by 和排序子句的减少时间;

2.缺点:

				(1)索引会占据一定发物理空间;
				(2)索引需要动态维护,进行数据操作时;

二、创建索引原则

  (1)不能在外键列建立索引;
  (2)在列值重复多的不要建立索引;
  (3)一般在多使用的group by 和order by 可以建立索引;
  (4)在待排序有多个列,可以建立复合索引(compound index);

三、使用步骤

1.创建索引—create index

1.允许有重复的索引值:
代码如下(示例): comlume_name =要索引的列名
create index index_name on table_name (comlume_name);
实例:
(1)#创建一个降序的索引:

create  index user_index on User (user_id   desc);  升序:asc

(2)#创建多个索引列: 用,隔开:

create  index  user_index  on User (user_id , user_name);

1.只能有唯一的索引值:
create unique index index_name on table_name (conlume_name);

2.使用索引

单索引:

index(a)
select * from table_name where a = ....  ;

联合索引:
遵循最左前缀匹配的原则,即*最左优先*
where子句中字段的顺序应和索引中字段顺序一致。

索引:index(a,b,c)
select * from table  where  a= ..  and b = ..   and c  = ..  ;
select * from table where  a=...;//用到索引
where a=3 and b=45 and c=5 .... 这种三个索引顺序使用中间没有断点,全部发挥作用;
where a=3 and c=5... 这种情况下b就是断点,a发挥了效果,c没有效果
where b=3 and c=4... 这种情况下a就是断点,在a后面的索引都没有发挥作用,这种写法联合索引没有发挥任何效果;

面试问题:有表table (a,b,c,d,e)单索引index(a),联合索引index(a,b,c)
以下哪个用到了索引:

  1. where a =A and c =C ;
  2. where a= A and b= B and c=C ;
  3. where a = A and b= B and c=C;
  4. wher e = E and a = A;

解答:1,2,3

四、撤销索引–drop

mysql

alter table_name drop index index_name ;

oracle & db2

drop index index_name ;

sql的优化

索引的角度——

  1. 条件范围的列 可能导致

缓存 内存 硬盘

分页查询——limit

分页实际上就是从结果集中“截取”出第M~N条记录

分页查询需要先确定每页的数量和当前页数

select * from table limit (当前页数-1*数量,数量; 
select * from table limit 数量 offset  (当前页数-1*数量

查询第4页的数据,每页十行

select * from table limit 30,10
select * from table limit 10 offset 30

总结

2022/3/9简单的描述了索引的创建、使用、删除;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值