gpt4 book ai didi

mysql - 如何识别最适合索引的列

转载 作者:行者123 更新时间:2023-11-29 05:54:27 25 4
gpt4 key购买 nike

我已经阅读了很多关于识别列的线程,这些列可能是创建索引的最佳候选者。但是,他们中的大多数建议在 JOIN 或 WHERE 子句中使用的列上创建索引。

不过,我不确定下面这样的复杂查询

select b.col1 ,a.col1 ,a.selectionId ,a.table2Id ,a.selectionName ,b.UserId,b.ParantId ,
a.teamType ,d.Name,b.isBack,b.SelectionId,b.Admin AS admin,
b.Master AS master,c.MstDate AS MstDate, c.col2
from tblselection a
join table1 c on c.col1 = a.col1
join table2 d on d.Id = a.table2Id
left join tabletest b on b.SelectionId = a.selectionId and a.table2Id = b.table2Id and b.IsMatched = 1
where ((ifnull(c.active,0) = 1) and isnull(b.Result) and isnull(b.ResultID))

对于此查询,哪些列最适合在所有 4 个表中建立索引?

我应该在这里创建复合索引还是单独索引?

最佳答案

使用前面的 EXPLAIN 关键字运行您的查询 (EXPLAIN SELECT b.cl1, a.col1 ...)。 MySQL 将为您详细说明事物是如何连接在一起的,以及它扫描了多少行来计算出来。

通常,您希望在被引用的列上建立索引,尤其是当它需要查看大量行或使用“表扫描”来连接它们时。你希望它说“使用主要”或“使用索引”

这是我的一个数据库的一些示例输出。你可以看到这个查询连接了 3 个表,但最终很快找到了它需要的东西,即使这些表相当大。每个子部分只需要引用一行:

+----+-------------+-------+------------+--------+---------------------+---------+---------+-------------------------------+------+----------+-------------+
| id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
+----+-------------+-------+------------+--------+---------------------+---------+---------+-------------------------------+------+----------+-------------+
| 1 | SIMPLE | sa | NULL | ref | choice_id,user_id | user_id | 5 | const | 1 | 100.00 | Using where |
| 1 | SIMPLE | qc | NULL | eq_ref | PRIMARY,question_id | PRIMARY | 4 | sa.choice_id | 1 | 100.00 | Using where |
| 1 | SIMPLE | q | NULL | eq_ref | PRIMARY | PRIMARY | 4 | qc.question_id | 1 | 100.00 | NULL |
+----+-------------+-------+------------+--------+---------------------+---------+---------+-------------------------------+------+----------+-------------+

关于mysql - 如何识别最适合索引的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51050088/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com