我正在尝试优化以下查询,该查询的执行时间约为 1.5 秒。
SELECT id
FROM leads
left join leads_cstm ON leads.id = leads_cstm.id_c
WHERE deleted=0
and cust_temp_id_c = 'xxxx';
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: leads_cstm
partitions: NULL
type: ALL
possible_keys: PRIMARY
key: NULL
key_len: NULL
ref: NULL
rows: 696334
filtered: 10.00
Extra: Using where
*************************** 2. row ***************************
id: 1
select_type: SIMPLE
table: leads
partitions: NULL
type: eq_ref
possible_keys: PRIMARY,idx_del_user,idx_leads_id_del
key: PRIMARY
key_len: 108
ref: crmsuite.leads_cstm.id_c
rows: 1
filtered: 50.00
Extra: Using where
2 rows in set, 1 warning (0.00 sec)
我尝试在leads_cstm(id_c,cust_temp_id_c)上创建索引,但没有成功!我也尝试使用 Straight_join,成本降低了,但查询现在需要更多时间来执行(3 秒)。
mysql> EXPLAIN SELECT id
FROM leads
STRAIGHT_JOIN leads_cstm ON leads.id = leads_cstm.id_c
WHERE deleted=0
and cust_temp_id_c = 'xxxxx';
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: leads
partitions: NULL
type: ref
possible_keys: PRIMARY,idx_del_user,idx_leads_id_del
key: idx_del_user
key_len: 2
ref: const
rows: 375820
filtered: 100.00
Extra: Using index
*************************** 2. row ***************************
id: 1
select_type: SIMPLE
table: leads_cstm
partitions: NULL
type: eq_ref
possible_keys: PRIMARY
key: PRIMARY
key_len: 108
ref: crmsuite.leads.id
rows: 1
filtered: 10.00
Extra: Using where
2 rows in set, 1 warning (0.00 sec)
请说明为什么使用直接联接时花费更多时间以及如何优化此查询。
两个表都包含大约 750000 行。
最佳答案
我假设 deleted
位于表 leads
和 leads_cstm
的 cust_temp_id_c
中。
要优化此查询,请尝试添加这两个索引:
ALTER TABLE `leads` ADD INDEX `leads_idx_deleted_id` (`deleted`,`id`);
ALTER TABLE `leads_cstm` ADD INDEX `leads_cstm_idx_c_c` (`cust_temp_id_c`,`id_c`);
然后运行查询:
SELECT
leads.id
FROM
leads
LEFT JOIN
leads_cstm
ON leads.id = leads_cstm.id_c
WHERE
leads.deleted = 0
AND leads_cstm.cust_temp_id_c = 'xxxx'
关于使用 Straight_Join 的 MySQL 查询成本更低,但执行时间更长,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50285679/