我有一个如下所示的查询:
select count(test.id) from table1
inner join table2 on table1.id = table2.id
where (table2.email = 'test@gmail.com'
OR (table2.phone1 IS NOT NULL AND table2.phone1 in ('123456'))
OR (table2.phone2 IS NOT NULL AND table2.phone2 in ('1234456')))
AND table2.id <> 1234
AND table2.created_at >= '2015-10-10'
AND table2.status NOT IN ('test')
AND table2.is_test = 'No';
我在 table2.email、table2.phone1、table2.phone2、table2.created_at 上有一个索引。这些都是单索引而不是复合索引。据我所知,(table2.email, table2.phone1, table2.phone2) 上的复合索引不起作用,因为条件是 OR 条件。我在 (table2.id, table2.created_at, table2.status, table2.is_test) 上创建了一个复合索引,但在解释查询中得到了相同的结果。解释查询如下所示
id select_type table type possible_keys key key_len ref rows Extra
1 SIMPLE table2 range PRIMARY, created_at 8 293 Using where
created_at,
email,
phone1,
phone2,
com_index
1 SIMPLE table1 eq_ref PRIMARY PRIMARY 4 id 1 Using index
这里 com_index 是我创建的复合索引。如何创建索引以加快此查询。从解释结果看,为查询选择的键是 created_at。有没有办法可以为表 2 创建复合索引?请帮我。提前致谢。
编辑:解释这个查询的生产:
+----+-------------+-------+--------+----------------------------------------------+---------+---------+----------------------+--------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+--------+----------------------------------------------+---------+---------+----------------------+--------+-------------+
| 1 | SIMPLE | l0_ | range | PRIMARY,created_at,email,day_phone,eve_phone | PRIMARY | 4 | NULL | 942156 | Using where |
| 1 | SIMPLE | m1_ | eq_ref | PRIMARY | PRIMARY | 4 | lead_platform.l0_.id | 1 | Using index |
+----+-------------+-------+--------+----------------------------------------------+---------+---------+----------------------+--------+-------------+