(Interview question) How to solve MySQL slow query

Causes and solutions for slow queries

  1. Scan for redundant data and avoid usingselect * from xxx
  2. Cross- 多表扫描data can be 减少joindenormalized appropriately to increase redundant data and trade space for time.
  3. 索引没有建立, the index is not optimized properly, or is not applied to the best index (the joint index uses the leftmost match)
CREATE TABLE `test_table`
`id` bigint(20) UNSINGED NOT NULL AUTO_INCREMENT,
`name` varchar(32) DEFAULT NULL,
`age` int(16) DEFAULT NULL,
KEY `idx_age`(`age`)
)ENGINE = InnoDB CHARSET = utf8mb4;
  1. The index created is inappropriate:
  • The index data type is simple and appropriate, takes up little space, and avoids NULL values ​​(NOT NULL) as much as possible, the better the performance.
  • Numeric types only need to be compared once, and strings will be compared verbatim; do not exceed 6 indexes, which will lead to performance degradation.
  • Fields with a lot of repeated data are not suitable for indexing, such as gender; random strings are not suitable for building clustered indexes (data movement)
  • Union index uses leftmost match
  • Index failure: avoid using or (use union all instead), in or not in (use exists instead), is null variable, matching query, or operator in the where clause, or perform expression and function operations on fields, %abc%otherwise !=it <>will Causes the engine to give up using the index and perform a full table scan
  1. cache:
  • Cache invalidation: SQL case sensitivity, query_cache_sizesize exceeded, insufficient memory, cache timeout, data modification
-- 不会使用同一缓存
select name from users where id = 1;
SELECT name FROM users WHERE id = 1;

References

  1. Solve MySQL slow query problem

Guess you like

Origin blog.csdn.net/e2788666/article/details/131447419