Buffer Pool 是 InnoDB 在内存里的缓存,数据页和索引页都缓存在这里。读的时候先看内存里有没有,没有再读磁盘;写的时候先改内存里的页,同时记 redo log,脏页由后台线程慢慢刷回磁盘。它是对性能影响最大的参数,专用的数据库服务器一般给到内存的一半到四分之三。它的淘汰算法是改进过的 LRU,分冷热两段,避免一次全表扫描把热点数据冲掉。
English PitchEnglish · ~55s
InnoDB is MySQL's default engine because it provides ACID transactions, row-level locking with MVCC, foreign keys, redo-log crash recovery, and a clustered index storing full rows in primary key B+ tree leaves. MyISAM lacks transactions, uses table-level locks, stores data separately from indexes, and risks crash corruption, so it's obsolete in production. The Buffer Pool is InnoDB's in-memory cache of 16 KB data and index pages: reads hit RAM first, while writes update cached pages plus the redo log and flush dirty pages asynchronously. Dedicated servers typically allocate 50–75% of RAM, and its young/old midpoint LRU stops full scans from evicting hot pages.
Key terms:InnoDB, clustered index, Buffer Pool, midpoint LRU
Likely follow-up: "Why shouldn't you set innodb_buffer_pool_size to 95% of host RAM, and how do you avoid cold-cache slowness after a MySQL restart?"
追问3 个
什么时候还会用 MyISAM?
几乎没有。只读的历史数据可以考虑,但 InnoDB 在绝大多数场景都不差。
Buffer Pool 设得越大越好吗?
不是,要给操作系统、连接线程的内存留余量,否则发生 swap 会更慢。
数据库重启后为什么一开始比较慢?
Buffer Pool 是空的,要重新从磁盘加载;MySQL 可以在关闭时保存、启动时恢复 Buffer Pool 中的页列表来预热。
Because InnoDB clusters rows by primary key and stores that key in every secondary index leaf, primary keys should be short, sequential, and immutable. Auto-increment BIGINT appends densely without page splits, but leaks business volume and isn't globally unique across shards. Random UUIDv4 is globally unique, yet triggers page splits, fragmentation, and secondary-index bloat—especially as CHAR(36). Time-ordered IDs like 64-bit Snowflake (BIGINT) or UUIDv7 (BINARY(16)) offer the best compromise. For columns, always use DECIMAL for money rather than floats, utf8mb4 to support emoji, CHAR only for fixed-length codes, UTC DATETIME over 2038-limited TIMESTAMP when needed, and NOT NULL by default.
Key terms:page split, UUIDv7, DECIMAL, utf8mb4
Likely follow-up: "If you want to keep an internal auto-increment BIGINT primary key without exposing sequential IDs in your public API, how do you design the schema?"
InnoDB uses B+ trees to minimize disk I/O: each 16 KB page stores over a thousand keys, so three or four levels index tens of millions of rows with upper levels hot in memory. Internal nodes hold only keys for high fan-out, while leaf nodes store data linked in a doubly-linked list for fast range scans; hash indexes lack ranges and red-black trees grow too tall. In InnoDB, the clustered index is the primary key tree storing full rows, whereas secondary indexes store only indexed columns plus the primary key—requiring a random-I/O table lookup unless covered.
联合索引按列的顺序排序:先按第一列,第一列相同再按第二列。所以查询必须从最左边的列开始才能用上索引,中间不能跳,遇到范围条件后,后面的列只能用来过滤,不能再缩小扫描范围。设计时把等值条件的列放前面,范围和排序的列放后面。覆盖索引是指查询需要的列都在索引里,不用回表,EXPLAIN 的 Extra 会显示 Using index,对高频查询提升很大。
正式解释
索引 idx(a, b, c):
查询条件
索引使用
a = 1
用到 a
a = 1 AND b = 2
用到 a、b
a = 1 AND b = 2 AND c = 3
全部用到
b = 2
用不上(跳过了最左列)
a = 1 AND c = 3
只用 a 定位;c 通过索引下推在索引内过滤
a = 1 AND b > 2 AND c = 3
a、b 用于定位,c 只能过滤
a = 1 ORDER BY b
用到 a,并且不需要额外排序
WHERE 中条件的书写顺序没有影响,优化器会调整。
设计原则(等值、排序、范围):
等值条件的列在前。
然后是排序、分组的列。
范围条件的列放最后。
区分度高的列更适合建索引;只有两三个取值的列单独建索引意义不大。
索引 (a, b) 已经包含了 (a) 的功能,不要重复建。
覆盖索引:
SQL
-- 索引 idx_user_status (user_id, status, created_at)SELECT status, created_at FROM orders WHERE user_id =42; -- 覆盖,不回表SELECT*FROM orders WHERE user_id =42; -- 要回表取其他列
二级索引天然包含主键,所以 SELECT id 也是覆盖的。这也是不要写 SELECT * 的原因之一。
索引下推(ICP):在存储引擎层用索引中已有的列先过滤,减少回表次数,Extra 显示 Using index condition。
面试口语版中文 · 约 85 秒
联合索引是按列的顺序来排的,比如索引是 a、b、c,那就是先按 a 排,a 相同的再按 b 排,b 相同再按 c 排。所以查询的时候必须从最左边的列开始用,这就是最左前缀。只有 b 的条件是用不上这个索引的,因为单看 b 是无序的。另外遇到范围条件以后,后面的列就不能再用来定位了,只能用来过滤。
设计联合索引的时候,我会把等值查询的列放前面,然后是排序用的列,范围条件的列放最后;区分度高的列优先。有了 a、b 的联合索引,就不用再单独建 a 的索引了。
覆盖索引是指查询要的列全部都在索引里,这样在二级索引上就能拿到结果,不用回表去取整行,EXPLAIN 里会显示 Using index。回表是随机 IO,所以对高频查询,把要查的列加到索引里做成覆盖索引,提升非常明显,这也是为什么不建议写 select 星号。
English PitchEnglish · ~55s
A composite index sorts keys left to right—A, then B, then C—so queries must follow the leftmost prefix rule for index lookups. Skipping the leading column breaks ordering, and after a range predicate like b > 10, trailing columns can still filter via Index Condition Pushdown but cannot narrow the scan range. I design composite indexes with equality columns first, then ORDER BY/GROUP BY, and range columns last, favoring high selectivity. A covering index includes every requested column (Using index in EXPLAIN), eliminating random-I/O table lookups on hot queries—a major reason to avoid SELECT *.
Key terms:leftmost prefix, covering index, Index Condition Pushdown, cardinality
Likely follow-up: "Does column order inside the WHERE clause matter for hitting a composite index, and what happens to ORDER BY c after a range on b?"
追问3 个
WHERE a = 1 AND b > 10 ORDER BY c 能用 (a, b, c) 避免排序吗?
Index misses fall into two buckets: broken query patterns and cost-based optimizer choices. Patterns that disable index lookups include wrapping an indexed column in a function or expression, implicit type or charset conversion—like comparing VARCHAR to an integer—leading-wildcard LIKE '%foo', skipping the leftmost prefix, or an unindexed OR branch. Even with valid predicates, the optimizer chooses a full table scan when selectivity is low (roughly over 15–20% of rows) because sequential scans beat thousands of random table lookups. Stale statistics also mislead it, so I check EXPLAIN, rewrite predicates or run ANALYZE TABLE, and avoid FORCE INDEX.
Key terms:implicit type conversion, cost-based optimizer, selectivity, ANALYZE TABLE
Likely follow-up: "Why might a query use an index in staging but suddenly fall back to a full table scan in production?"
ACID defines transactional guarantees, and InnoDB enforces them with distinct storage-engine mechanisms. Atomicity—all-or-nothing execution—relies on the undo log, which records pre-change images so rolled-back or crashed uncommitted transactions can be reversed. Durability relies on the redo log using Write-Ahead Logging: on commit, InnoDB sequentially flushes redo entries to disk rather than dirty data pages (keeping innodb_flush_log_at_trx_commit = 1 in production), replaying them on crash recovery. Isolation combines MVCC for non-blocking reads with row-level locks for concurrent writes. Finally, Consistency is the end invariant upheld by those three mechanisms together with schema constraints and application logic. In practice, I also keep transactions short to avoid lock contention and undo log bloat.
SQL defines four isolation levels: Read Uncommitted allows dirty reads; Read Committed prevents dirty reads but allows non-repeatable reads; Repeatable Read—InnoDB's default—keeps reads consistent within a transaction; and Serializable serializes access at heavy concurrency cost. InnoDB enables non-blocking reads via MVCC: each row tracks DB_TRX_ID and a rollback pointer chaining older versions in the undo log. Snapshot reads build a Read View of active transaction IDs and walk the chain to a visible version. Read Committed creates a fresh Read View per statement, while Repeatable Read reuses the first one—and locking reads like FOR UPDATE bypass MVCC.
FOR SHARE 加 S;FOR UPDATE、UPDATE、DELETE 加 X;S 与 S 兼容,其余互斥
记录锁(Record Lock)
一条索引记录
防止被修改、删除
间隙锁(Gap Lock)
索引记录之间的开区间
防止插入;间隙锁之间不互斥,只阻塞插入
Next-Key Lock
记录 + 它之前的间隙,左开右闭
可重复读下当前读的默认加锁单位,防幻读
插入意向锁
待插入的间隙
插入前申请,被间隙锁阻塞
意向锁 IS / IX
表级
标记“表里有行锁”,让表锁不用逐行检查
元数据锁 MDL
表结构
读写数据时加读锁,DDL 加写锁;长事务会堵住 DDL,进而堵住所有后续请求
加锁规则(可重复读,简化):
唯一索引等值命中 → 退化为记录锁。
唯一索引等值未命中 → 所在的间隙锁。
非唯一索引等值 → 匹配记录的 next-key lock,外加后面的间隙。
范围查询 → 扫描到的范围都加 next-key lock。
没有可用索引 → 扫描聚簇索引,所有行和间隙都被锁住。
读已提交级别下没有间隙锁(外键和唯一性检查除外),且无索引更新时不符合 WHERE 条件的行锁会被提前释放,这是它锁冲突少的原因。
悲观锁与乐观锁:
SQL
-- 悲观锁:先锁再改SELECT stock FROM item WHERE id =1FORUPDATE;
-- 乐观锁:不加锁,更新时检查版本UPDATE item SET stock = stock -1, version = version +1WHERE id =1AND version =5;
MySQL 8.0 的 FOR UPDATE NOWAIT 拿不到锁立即报错,SKIP LOCKED 跳过已被锁的行,适合实现任务队列。
读已提交级别下基本没有间隙锁,所以锁冲突和死锁会少很多。另外还有元数据锁,一个长事务没提交,会把 ALTER TABLE 堵住,然后后面所有的查询也跟着被堵住。
English PitchEnglish · ~55s
InnoDB places row locks on index records rather than raw table rows. Beyond shared and exclusive modes, there are three forms: a Record Lock locks one index entry, a Gap Lock locks the open interval between entries to block inserts and prevent phantoms, and a Next-Key Lock combines both as Repeatable Read's default. An exact match on a unique index degrades to a Record Lock, while non-unique or range predicates take Next-Key Locks. In production, an unindexed UPDATE or DELETE locks every scanned row and gap, stalling the table—and switching to Read Committed drops most gap locks to cut deadlocks.
Key terms:Record Lock, Gap Lock, Next-Key Lock, metadata lock
Likely follow-up: "Two transactions both hold a Gap Lock on the same range and then try to insert—why does that cause a deadlock?"
死锁是两个事务各自持有对方需要的锁并互相等待,典型原因是以相反顺序更新同样的行。InnoDB 会自动检测并回滚其中一个,返回 1213 错误,应用应捕获后重试。排查用 SHOW ENGINE INNODB STATUS 看两个事务持有和等待的锁。避免办法是按固定顺序访问、事务短小、更新走索引。锁等待超时是另一回事:只是等锁太久,通常因为有长事务。
正式解释
示意
事务 A:UPDATE acct SET ... WHERE id = 1; 事务 B:UPDATE acct SET ... WHERE id = 2;
事务 A:UPDATE acct SET ... WHERE id = 2;(等 B)事务 B:UPDATE acct SET ... WHERE id = 1;(等 A)→ 死锁
死锁(Deadlock)
锁等待超时(Lock wait timeout)
错误
1213 Deadlock found when trying to get lock
1205 Lock wait timeout exceeded
原因
循环等待
单向等待太久(长事务、大批量更新、忘记提交)
发现
立即(innodb_deadlock_detect)
等满 innodb_lock_wait_timeout(默认 50 秒)
结果
回滚其中一个事务
默认只回滚当前语句,事务仍然开着
常见的死锁场景:两个事务以相反顺序更新行;间隙锁:可重复读下两个事务先对不存在的记录做加锁读(如 SELECT ... FOR UPDATE)或写操作(都拿到同一间隙的间隙锁),再各自插入;通过不同的二级索引更新同一批行,加锁顺序不同;批量 INSERT ... ON DUPLICATE KEY UPDATE。
死锁是两个事务互相拿着对方要的锁,都在等对方。最典型的例子是事务 A 先更新 id 等于 1 再更新 2,事务 B 先更新 2 再更新 1,顺序相反,同时执行就死锁了。还有一种常见的是间隙锁导致的:在可重复读下,两个事务都用 SELECT ... FOR UPDATE(或 UPDATE/DELETE)去查改同一条不存在的记录,都拿到了同一个间隙的间隙锁,然后各自插入时互相等待对方释放间隙锁,就死锁了。
InnoDB 有死锁检测,发现以后会挑一个回滚代价小的事务回滚掉,报 1213 错误,所以应用要捕获这个错误然后重试。排查的话,show engine innodb status 里有最近一次死锁的详细信息,能看到两个事务的 SQL、各自拿着什么锁、在等什么锁。
A deadlock is a circular wait—commonly from two transactions updating rows in opposite orders, or in Repeatable Read taking gap locks on a missing row and then inserting. InnoDB detects it immediately and rolls back the cheaper victim with error 1213, which applications should catch and retry idempotently. I diagnose deadlocks using SHOW ENGINE INNODB STATUS (or innodb_print_all_deadlocks) to inspect held and waited locks, and prevent them with consistent lock ordering, short transactions, indexed writes, and Read Committed when gap locks aren't needed. By contrast, a 1205 lock wait timeout is a one-way wait—usually a stuck long transaction found in innodb_trx.
Likely follow-up: "When a 1205 lock wait timeout fires in InnoDB, is the whole transaction rolled back by default, and when might teams intentionally disable deadlock detection?"
When reading EXPLAIN, I check four fields first. type shows the access path from best to worst—const, eq_ref, ref, range, index, down to ALL for a full table scan. key and key_len reveal the chosen index and how many composite columns were used, while rows estimates scanned rows. Finally, Extra surfaces hidden costs: Using index confirms a covering index, whereas Using filesort or Using temporary flags extra sorting or temp-table work. Because EXPLAIN relies on statistics, I run EXPLAIN ANALYZE on realistic data to verify actual row counts and step timings.
Key terms:EXPLAIN ANALYZE, access type, Using index, Using filesort
Likely follow-up: "If EXPLAIN shows low estimated rows and a valid index, why might the query still be slow in production?"
一直慢一般是 SQL 本身的问题。先从慢查询日志里把它找出来,然后 EXPLAIN。常见的情况有:没走索引,全表扫描,那就加索引,或者看是不是在列上用了函数、发生了隐式转换导致索引失效;走了索引但扫描行数还是很多,要回表很多次,可以做成覆盖索引;有 filesort 或者临时表,看能不能让排序用上索引;还有深分页,limit 一百万、二十,要先扫一百万行再丢掉,应该改成按上一页最后一个 id 往后取。
偶尔慢一般不是 SQL 的问题,而是当时的环境:可能在等锁,有长事务;可能 Buffer Pool 不够,数据要从磁盘读;也可能是在刷脏页,或者整台机器负载高。这时候要看 processlist、锁等待和系统监控。
优化的时候我会优先处理总耗时最高的语句,而不是只看单次最慢的;加索引也要考虑它对写入的影响。
English PitchEnglish · ~55s
I first distinguish whether a query is consistently slow or only intermittently slow. Consistently slow queries point to SQL or indexing issues: I pull top offenders by total latency from the slow query log, run EXPLAIN ANALYZE, and fix full scans, broken index predicates, heavy table lookups with covering indexes, filesort, or deep OFFSET pagination via keyset cursors. Intermittent spikes indicate runtime contention—lock waits from long transactions, Buffer Pool misses, dirty-page flushing, or host I/O saturation—diagnosed via SHOW PROCESSLIST and lock-wait views. I always validate fixes on production-scale data and weigh new indexes against write amplification.
Key terms:slow query log, keyset pagination, lock wait, Buffer Pool
Likely follow-up: "How do you optimize deep pagination like LIMIT 1000000, 20 when product requirements still need arbitrary page jumps?"
MySQL supports INNER JOIN for matched rows, LEFT/RIGHT JOIN to keep all rows from one side with NULL-padded columns for unmatched rows (for LEFT JOIN, keep right-table filters in ON rather than WHERE, or you turn it into an inner join), and CROSS JOIN, while emulating FULL OUTER JOIN via UNION. For execution, MySQL prefers Index Nested-Loop Join—scanning the smaller driving set and probing an indexed join key on the driven table—and falls back to Hash Join in MySQL 8.0 for unindexed equi-joins. As for counts, COUNT(*) and COUNT(1) perform identically and count all rows, whereas COUNT(col) ignores NULLs. Because MVCC gives each transaction a different snapshot, InnoDB doesn't store total row counts and scans the smallest secondary index instead.
MySQL replication streams changes via the binlog: the primary writes committed row events to its binlog, a replica's I/O thread pulls them into its local relay log, and its SQL thread replays them. By default, replication is asynchronous—fast, but a sudden primary crash can lose unshipped commits—whereas semi-synchronous waits for at least one replica to acknowledge receipt at the cost of an extra network round-trip. With read-write splitting, replication lag breaks read-your-writes consistency. To handle it, I route critical reads and short post-write user windows to the primary, wait on a specific GTID when needed, and shrink lag itself by breaking up large transactions and enabling parallel replication on replicas.