【问题标题】:mysql query not using the index i wantmysql查询不使用我想要的索引
【发布时间】:2011-03-07 23:33:35
【问题描述】:

我有以下查询加入 2 个表:

explain 

    select 
        n.* from npi n left join npi_taxonomy nt on n.NPI=nt.NPI_CODE 

    where 
        n.Provider_First_Name like '%s%' and 
        n.Provider_Last_Name like '%b%' and 
        n.Provider_Business_Practice_Location_Address_State_Name = 'SC' and 
        n.Provider_Business_Practice_Location_Address_City_Name = 'charleston' and 
        n.Provider_Business_Practice_Location_Address_Postal_Code in (29001,29003,29010,29016,29018,29020,29030,29032,29033,29038,29039,29040,29041,29042,29044,29045,29046,29047,29048,29051,29052,29053,29056,29059,29061,29062,29069,29071,29072,29073,29078,29079,29080,29081,29082,29102,29104,29107,29111,29112,29113,29114,29115,29116,29117,29118,29123,29125,29128,29133,29135,29137,29142,29143,29146,29147,29148,29150,29151,29152,29153,29154,29160,29161,29162,29163,29164,29168,29169,29170,29171,29172,29201,29202,29203,29204,29205,29206,29207,29208,29209,29210,29212,29214,29215,29216,29217,29218,29219,29220,29221,29222,29223,29224,29225,29226,29227,29228,29229,29230,29240,29250,29260,29290,29292,29401,29402,29403,29404,29405,29406,29407,29409) and 
        n.Entity_Type_Code = 1 and 
        nt.Healthcare_Provider_Taxonomy_Code in ('101Y00000X') 

    limit 0,10; 

我添加了一个多列索引:

npi_fname_lname_state_city_zip_entity 在表 npi 上按以下顺序索引列:

NPI,  
Provider_First_Name, 
Provider_First_Name, 
Provider_Business_Practice_Location_Address_State_Name, Provider_Business_Practice_Location_Address_City_Name, Provider_Business_Practice_Location_Address_Postal_Code, 
Entity_Type_Code

但是,当我对查询进行解释时,它显示它使用主索引 (NPI)。此外,它说检查的行 = 1

更糟糕的是:执行查询大约需要 120 秒。我该如何优化呢?

我非常感谢您对此的帮助。

【问题讨论】:

标签: mysql indexing query-optimization


【解决方案1】:

您的多列索引没有帮助的原因是因为您使用通配符like '%s%' 进行过滤。

索引只能在使用索引的最左前缀过滤时使用,这意味着1)cannot do a contains search,以及2)如果多列索引的最左列不能已使用,索引中的其他列 cannot be used aswell。

您应该将索引中列的顺序切换为

Provider_Business_Practice_Location_Address_State_Name, 
Provider_Business_Practice_Location_Address_City_Name, 
Provider_Business_Practice_Location_Address_Postal_Code, 
Entity_Type_Code

这样,MySql 将只扫描与那些列(SC、charleston 等)的条件匹配的行。

或者,查看full text indexes。

【讨论】:

    猜你喜欢
    • 2012-04-26
    • 2013-07-10
    • 2020-10-25
    • 1970-01-01
    • 2021-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多