MySQL查询优化,不使用主键索引?
我们有很多这样的问题,但是每个查询都是唯一的,所以这个问题就出现了。我有以下疑问MySQL查询优化,不使用主键索引?,mysql,database,Mysql,Database,我们有很多这样的问题,但是每个查询都是唯一的,所以这个问题就出现了。我有以下疑问 Select * from tblretailerusers where (company_id=169 or company_id in (select id from tblretailercompany where multi_ret_id='169')) and ( id in (Select contact_person_1 from tbllocations where status=1 and (re
Select * from tblretailerusers where (company_id=169 or company_id in (select id from tblretailercompany where multi_ret_id='169')) and ( id in (Select contact_person_1 from tbllocations where status=1 and (retailer_comp_id=169 or retailer_comp_id in (select id from tblretailercompany where multi_ret_id='169'))) OR id in(Select contact_person_2 from tbllocations where status=1 and (retailer_comp_id=169 or retailer_comp_id in (select id from tblretailercompany where multi_ret_id='169'))) ) and (last_login is not null )
它有三个表:零售商、他们的位置和他们的用户。标准用户信息。每个零售商都可以有子零售商,所以零售商表有父零售商ID。目前每个表有大约6K条记录,所有表都有主键作为自动增量,据我所知,它们也被索引。在用户表中,电子邮件字段被索引
现在,这个查询需要<1秒,这很好,但现在客户端希望找到其电子邮件ID以特定字母开头的用户,如a
和b
。一旦我将其添加到查询中,它就开始花费大约50-60秒的时间。我在Email字段上创建了索引,它不是唯一的,新的查询如下
Select * from tblretailerusers where (company_id=169 or company_id in (select id from tblretailercompany where multi_ret_id='169')) and ( id in (Select contact_person_1 from tbllocations where status=1 and (retailer_comp_id=169 or retailer_comp_id in (select id from tblretailercompany where multi_ret_id='169'))) OR id in(Select contact_person_2 from tbllocations where status=1 and (retailer_comp_id=169 or retailer_comp_id in (select id from tblretailercompany where multi_ret_id='169'))) ) and (last_login is not null ) and email REGEXP '^A|^B'
我尝试使用Explain,在查询的两个版本中,我注意到一个有趣的事实是,在主表行中,它没有显示可能的\u key
的任何值,因为我们在用户表中使用主键id
搜索,而且我在Email字段上也有索引。以下是查询的解释:
我尝试重新创建索引,当前我有一个索引,它使用ID、CompanyID和电子邮件,而不是用户表中的主键。我也在公司表上创建索引,但没有任何加快速度。用户表是MyISAM
我的另一个问题是,如何跳过子公司搜索的子查询,正如您可以看到的,在上面的查询中,它被使用了三次
EDIT:我在查询中使用REGEXP的原因是,当我尝试像“A%”这样的时,该选项的速度甚至很慢
编辑我只是用上一次登录为空
而不是上一次登录不为空
进行测试,结果耗时不到5秒。不为Null或不为Null类似吗?不使用正则表达式:
and email REGEXP '^A|^B'
…尝试一个简单的方法,如:
and (email like 'A%' or email like 'B%')
正则表达式对于这个相当小的比较来说有点沉重。Like可能会快得多。此外,我也不希望乐观主义者尝试解码regexp试图做的事情。但是,对于Like,它知道并且可能会使用您设置的索引。很抱歉,我忘了提到我在Like%
之后选择了regexp
,这会占用更多的工作时间。