代码之家  ›  专栏  ›  技术社区  ›  Adam Tegen

高效的数据库搜索,如“%something%”

sql
  •  3
  • Adam Tegen  · 技术社区  · 15 年前

    我正试图通过电话号码搜索任何包含一系列数字的电话号码。

    显然,下面的过程会很慢:

     Select * from customer where phone like '%1234%'
    

    注意:我已经通过删除所有非数字字符创建了“已清理”的电话号码,所以我不必担心破折号、空格等。

    有什么魔法能让这样的搜索在合理的时间内运行吗?

    2 回复  |  直到 15 年前
        1
  •  2
  •   Joshua    15 年前

    如果您使用的是MySQL,那么您需要的是全文搜索功能 http://dev.mysql.com/doc/refman/5.1/en/fulltext-search.html

    我在生产中使用过,效果很好。

        2
  •  1
  •   Will Hartung    15 年前

    如果你愿意,你可以做一个索引表。会有点贵,但也许值得。

    1
    2
    5
    12
    21
    25
    51
    55
    121
    125
    212
    255
    512
    551
    555
    1255
    2125
    2555
    5121
    5512
    5551
    12555
    21255
    25551
    55121
    55512
    125551
    212555
    255512
    555121
    1255512
    2125551
    2555121
    12555121
    21255512
    212555121
    2125551212
    

    例如:

    create table myindex (
        key varchar(10) not null,
        datarowid integer not null references datarows(id)
    );
    create index i1myindex(key);
    insert into myindex values('1255', datarow.id);
    

    例如,您可以只深入4,然后扫描具有4个数字的结果。

    因此,例如,如果有“%123456%”,则可以请求具有“1234”的键,然后对结果集应用完整表达式。

    比如:

    select d.* from datarows d, myindex i where i.datarowid = d.id and i.key = '1234' and d.phone like "%123456%";
    

    索引应该能帮助你很快缩小范围,db会扫描剩下的部分。

    显然,您将在这里生成一些数据,但是如果您进行大量查询,您可以在这里获得一些性能。