数据库常见面试题-索引

273 阅读2分钟

这是我参与更文挑战的第19天,活动详情查看: 更文挑战

一、索引 (index)
show index from table / 显示所有索引

createunique) index xx on/ 创建索引

alter table xxx add index indexName/ 添加索引

drop index  on table/ 删除索引

索引是什么呢,打个比方,图书馆里有一万本书,我们可以用每本书名中的每个字的拼音首字母作为排序规则建立目录(索引),从而快速的查找到书的位置。

优点:提高查询速度;

缺点:降低更新速度,为什么这么说呢,索引本身也是表,因此会占用存储空间,一般来说,索引表占用的空间的数据表的1.5倍;索引表的维护和创建需要时间成本,这个成本随着数据量增大而增大;构建索引会降低数据表的修改操作(删除,添加,修改)的效率,因为在修改数据表的同时还需要修改索引表;

实际开发中,应该结合业务场景和用户使用习惯去考虑是否要加索引,比如日期、user_id这些字段,用户查的频次较多,也容易被开发忽略。

二、慢查询

攻克慢查询,提高查询速度,可以建立索引。

设置慢查询日志:

mysql -uroot -p

show variables like 'slow_query%';

show variables like 'long_query_time';

 slow_query_log   | OFF

set global slow_query_log='ON'; 

set global slow_query_log_file='/var/lib/mysql/test-10-226-slow.log';

查询超过1秒就记录

set global long_query_time=1;

编辑配置文件/etc/my.cnf加入如下内容

[mysqld]

**slow_query_log = ON**

**slow_query_log_file = /var/lib/mysql/test-10-226-slow.log**

**long_query_time = 1

修改配置后重启mysql

systemctl restart mysqld

mysql -uroot -p

使用下面命令验证

show variables like 'slow_query%'

mysql永久开启了慢查询日志功能

三、常用查询方式

group by 分组

按列成员划分开,select 列名/列名函数 from where group by/having/order by

左外连接

select * from A left join B on xxx; A全部数据 B表只有部分数据

右外连接

select * from A right join B on xxx; B显示全部数据,A表只有部分数据

内连接

select * from A inner join B on xxx; 只显示A和B完全匹配上的数据

子查询

SELECT * FROM emp WHERE sal > (SELECT sal FROM emp WHERE ename = 'CLARK')

order by 排序

随机取出10条数据

select top 10 * from tablename order by newid();

四、分页查询

--写法1,not in/top

select top 50 * from pagetest

where id not in (select top 9900 id from pagetest order by id)

order by id

--写法2,not exists

select top 50 * from pagetest

where not exists

(select 1 from (select top 9900 id from pagetest order by id) a where a.id=pagetest.id)

order by id

五、聚合数:avg ,sum ,max ,min , count ,count(*)

AVG:求平均值

SUM:求和

MAX:求最大值

MIN:求最小值

COUNT(*):返回所有行数