gpt4 book ai didi

MySQL - 基本的 2 表查询速度慢 - 索引在哪里?

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

我有一个 MySQL 5.0 查询,通常需要 14 秒以上,从网页调用,用户不耐烦。这很简单,从 2 个表中选择 11 列。我有三个问题:

  1. 加入的位置重要吗?
  2. where 子句的顺序重要,还是 MySQL 会优化?
  3. 索引对我的情况有帮助吗?

SQL:

select table1.id, table1.DateOpened, table1.Status, table2.Name, etc
from (table1 join table2 on((table1.CurrentName = table2.id)))
where table1.Type = 'Add' and (Status = 'Open' OR Status = 'Pending');

表/列信息:

table1 has 750,000 rows, table2 1.5M rows.
indexed: table1.id, table2.id
INT columns: id, table1.CurrentName
table1.Status = always populated with 1 of 4 values,
maybe 300 are 'Open' or 'Pending'
table1.Type = 3 possible values: 'Add', 'Change', or null
  1. 与在 WHERE 子句中添加“table1.CurrentName = table2.id”相比,在 FROM 中加入 JOIN 有什么优势吗?

  2. 有 3 个 WHERE 子句(带连接)。我用各种顺序组合运行 EXPLAIN,结果似乎是一样的。

  3. 我认为向 table1.CurrentName 添加索引可能会有帮助,但现在我认为没有帮助。我修改了查询以删除对 table2 的引用,但它仍然运行缓慢。 (见 3b)

  4. 似乎大部分减速可能只是读取 800K 记录以查看类型和状态值。对只有 3 或 4 个可能值的这两列进行索引是否有意义?我认为只有当有更多独特的值(value)时才有意义。

解释结果:

+----+-------------+--------+--------+---------------+---------+---------+-----------------------+--------+-------------+ 
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+--------+--------+---------------+---------+---------+-----------------------+--------+-------------+
| 1 | SIMPLE | table1 | ALL | CurrentName | NULL | NULL | NULL | 733190 | Using where |
| 1 | SIMPLE | table2 | eq_ref | PRIMARY | PRIMARY | 4 | db.table1.CurrentName | 1 | |
+----+-------------+--------+--------+---------------+---------+---------+-----------------------+--------+-------------+
2 rows in set (0.00 sec)

最佳答案

Does placement of join matter?

它们的写入顺序对于 INNER JOIN 无关紧要。

Does order of where clause matter, or will MySQL optimize?

没有。 WHERE 子句中的书写顺序对 MySQL 查询解析器和优化器没有影响

Would and index help in my case?

有可能。 table1 上的复合索引 type_status (Type, Status) 可能会有所帮助,因为这是您的 WHERE 子句可以减少读取的初始行的地方。

Is there any advantage JOINing in the FROM, vs adding 'table1.CurrentName = table2.id' in the WHERE clause?

对于 INNER JOIN,JOIN 条件是在 FROM 子句中还是在 WHERE 子句中并不重要。

I thought adding an index to table1.CurrentName may help, but now I'm thinking not. I modified the query to remove references to table2, and it still ran slow. (see 3b)

table1.CurrentName 上的索引对查询没有帮助。

Seems like the bulk of the slowdown may be just reading 800K records looking at the Type and Status values.

这强化了我上面的想法。要添加复合索引(在网上做可能不是一件好事),就像

ALTER TABLE table1 ADD INDEX type_status (Type, Status);

I thought it only made sense when there were more unique values.

选择性肯定有帮助,但高基数并不是唯一合适的上下文。

关于MySQL - 基本的 2 表查询速度慢 - 索引在哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4328986/

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