【发布时间】:2018-10-17 10:11:02
【问题描述】:
最近我在检查我的系统日志,发现我的一些查询非常慢。
我有一个存储用户活动的表。表结构为id (int), user (int), type (int), object (varchar), extra (mediumtext) and date (timestamp)。
我也只有id (BTREE, unique)的索引。
我有以下查询的性能问题;
SELECT DISTINCT object as usrobj
from ".MV15_PREFIX."useractivities
WHERE user='".$user_id."'
and type = '3'
limit 0,1000000"
问题是,我是否也应该将user 与id 索引相同?我应该遵循的最佳做法是什么?
此表已被积极使用,其中包含超过 500k+ 行。并且网站平均有 2k~ 并发用户在线。
我问这个问题的原因是我不太擅长管理数据库,而且我在另一个具有正确索引的表上查询速度很慢。
提前感谢您的建议。
旁注:
mysqltuner的结果
一般建议:
Reduce or eliminate persistent connections to reduce connection usage
Adjust your join queries to always utilize indexes
Temporary table size is already large - reduce result set size
Reduce your SELECT DISTINCT queries without LIMIT clauses
Consider installing Sys schema from https://github.com/mysql/mysql-sys
要调整的变量:
max_connections (> 768)
wait_timeout (< 28800)
interactive_timeout (< 28800)
join_buffer_size (> 64.0M, or always use indexes with joins)
(我将设置max_connections > 768,不太确定超时,就我在 Stackoverflow 中阅读的主题/建议而言,我认为我不应该增加 join_buffer_size 的大小,但我非常感谢您也能获得有关这些变量的反馈。)
编辑 - 显示索引结果;
+--------------------+------------+-----------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment |
+--------------------+------------+-----------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| ***_useractivities | 0 | PRIMARY | 1 | id | A | 434006 | NULL | NULL | | BTREE | | |
| ***_useractivities | 1 | user_index | 1 | user | A | 13151 | NULL | NULL | | BTREE | | |
| ***_useractivities | 1 | user_type_index | 1 | user | A | 10585 | NULL | NULL | | BTREE | | |
| ***_useractivities | 1 | user_type_index | 2 | type | A | 13562 | NULL | NULL | | BTREE | | |
+--------------------+------------+-----------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
【问题讨论】:
-
请注意,没有 ORDER BY 的 LIMIT 是毫无意义的
-
所有调谐器建议与关于索引的问题无关。
标签: mysql database mariadb query-performance