【问题标题】:How to optimize where query with enum type如何使用枚举类型优化 where 查询
【发布时间】:2020-08-16 01:26:55
【问题描述】:

我有比较简单的查询:

 select client_coordinator_id
    from projects 
    where status not in ("DELETED", "ARCHIVED")
    and client_coordinator_id > 0
    group by client_coordinator_id

projects表大约有320k条记录,client_coordinator_idstatus列都有索引,查询仍然需要0.7秒左右。

状态是ENUM类型。

EXPLAIN 给出了这个:

id - 1
select_type - SIMPLE
table - projects 
partitions - null
type - index
possible_keys - status,client_coordinator_idx,status_project_batch_id_idx,idx_status_new_status_id
key - client_coordinator_idx
key_len - 4
ref - null
rows - 311837
filtered - 40.00
Extra - using where

我在这里做错了什么?知道这个查询有什么问题吗?

【问题讨论】:

  • 我猜您使用group by client_coordinator_id 删除重复项。而是尝试select distinct client_coordinator_id 并检查是否有任何改进。

标签: mysql sql select query-optimization where-clause


【解决方案1】:

client_coordinator_id 和 status 列都有索引

我会建议在两列上都使用索引,而不是在每列上使用单独的索引。所以:

create index ix_projects on projects(status, client_coordinator_id)

这应该是正确的列顺序,但您也可以尝试:

create index ix_projects on projects(client_coordinator_id, status)

尝试每个索引,然后删除它并尝试下一个 - 不要同时尝试两个索引,否则您将无法判断哪个索引有帮助。

也很不清楚您为什么使用group by,但select 子句中没有出现聚合函数。大概,你想要select distinct。这不一定会提高性能,但这会使意图更加清晰:

select distinct client_coordinator_id
from projects 
where status not in ('DELETED', 'ARCHIVED')
and client_coordinator_id > 0

【讨论】:

  • 第二个索引帮助很大 - 它下降到 0.09 秒。非常感谢 :)。当使用 distinct 时,查询会明显变慢(它比原始查询慢)。使用 group by 它会下降到 0.09 秒。
猜你喜欢
  • 2016-07-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-10
  • 2020-09-14
  • 1970-01-01
  • 1970-01-01
  • 2017-11-05
相关资源
最近更新 更多