[toc]
事务四大特性
ACID 四大特性:
- Atomic 原子性,一个事务中的所有操作要么全部成功,要么全部失败回滚
- Consistency 一致性,事务开始和提交后,数据库的完整性约束没有被破坏
- Isolation 隔离性,多个连接并发访问数据库时,并发的不同事务之间不能相互干扰
- Durability 持久性,一旦一个事务被提交了,那么对数据库中的数据的改变就是永久性的
事务的并发会带来哪些问题?
数据丢失:事务A修改但未提交的数据,被事务B所覆盖,造成数据丢失
脏读:事务B读取了事务A修改但是并未提交的数据,之后事务B回滚,事务A读到的就是脏数据
不可重复读:事务B在一个事务中多次读取同一条数据,但该数据在两次读之间被A事务修改并提交,B事务出现了前后两次读,读到的数据不一致的情况
幻读:事务B前后两次进行范围查询时,两个 query 之间,事务A在该范围内插入了一条数据,导致事务B前后两次查询结果不一致,多出一条数据
隔离级别?
- 读未提交 READ-UNCOMMITTED
- 不可重复读 READ-COMMITTED
- 可重复读 REPEATABLE-READ
- 串行化 SERIALIZABLE
其中,不可重复读解决了脏读的问题,未提交的修改不会被其他事务看到(快照读?);可重复读解决了不可重复读的问题,当前事务读取的数据不可以被其他事务修改,试图修改数据的事务会被阻塞;可串行化解决了幻读问题,各个事务串行执行,不存在并发问题。
MySQL 隔离级别
MySQL 支持四种隔离级别,其中 innoDB 存储引擎默认的隔离级别是 RR,可重复读。
innoDB 通过 MVCC 和间隙锁 next-key lock 解决了 RR 隔离级别下幻读的问题。
MyISAM 和 innoDB 的区别
主要的区别在于以下几个方面:
- innoDB 支持事务,MyISAM 不支持事务
- innoDB 默认使用行锁,MyISAM 使用表锁
- innoDB 缓存索引和数据,MyISAM 只缓存索引,指向数据行的物理地址
- innoDB 支持外键
MyISAM 节省内存,加表锁开销小,但是不适合并发写的场景,以及需要用到事务的场景。
innoDB 是 MySQL 默认存储引擎。
MySQL B+树索引和 Hash 索引的区别
- Hash 索引检索效率非常高,检索只需要一次磁盘 I/O
- B+树索引需要从根节点到叶子节点,每次查询可能需要多次磁盘 I/O
为什么用B+树而不用哈希索引
- 由于 hash 索引无序,因此不能范围查询,在排序操作的时候也无法使用 hash 索引
- Hash 索引不能利用部分索引键查询,因为 hash 索引在计算 hash 值时,先将索引键合并再计算哈希值
- 由于不同的索引键可能存在相同的哈希值,所以无法利用 hash 索引直接完成查询,无法避免表扫描
- 极端情况下,hash 表某个桶中的链表特别长的时候,索引效率会更低
MySQL 中,只有 HEAP/MEMORY 引擎才显式支持 hash 索引。
总结
等值查询且键值唯一,那么哈希索引具有优势;如果需要范围查询或者排序,那么哈希索引会失效。
聚集索引与非聚集索引
根本区别:
表记录的排列顺序和索引的排列顺序是否一致。
聚集索引表记录的排列顺序和索引的排列顺序一致,又称为主索引,可以建立在任何字段上。
非聚集索引表记录的排列顺序和索引的排列顺序不一致,又称为辅助索引。
优缺点
由于聚集索引中索引与数据文件合并,索引字段所在的行数据存在索引叶子节点中,因此在插入数据的时候可能需要对索引节点进行分裂重排,影响效率,然而在没有重排的情况下,聚集索引可以通过索引直接访问数据,而不需要通过指针再去数据文件中读取数据,造成多余的磁盘IO。