mariadb-我应该向表中添加索引吗?

wn9m85ua  于 2021-06-25  发布在  Mysql
关注(0)|答案(2)|浏览(280)

最近我在检查我的系统日志,我发现我的一些查询非常慢。
我有一个存储用户活动的表。表结构是 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      |         |               |
+--------------------+------------+-----------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
pcrecxhr

pcrecxhr1#

这些postgresql索引的经验法则大多适用于大多数sql数据库管理系统。
https://dba.stackexchange.com/a/31517/1064
所以,是的,你可能会受益于 user 还有一个索引 type . 您可能会从对的索引中受益更多 user, type .
学习如何阅读执行计划也会让你受益匪浅。

lpwwtiir

lpwwtiir2#

对于该查询,以下任一项都是最佳的:

INDEX(user, type)
INDEX(type, user)

单独索引( INDEX(user), INDEX(type) )很可能不是那么好。
mysql的innodb只有 BTree ,不是 Hash . 不管怎样,btree基本上和hash一样适用于“点查询”,而对于“范围”查询则要好得多。
索引提示。
索引帮助 SELECTs 以及 UPDATEs ,有时很多。使用它们。副作用很小,比如占用了额外的磁盘空间。

相关问题