mysql: efficient way for postfix-search (like '%text' aka. prefix wildcard)?

后端 未结 2 1865
庸人自扰
庸人自扰 2020-12-31 19:21

Is there any build-in functionality in MySQL to do the above without scanning the entire table?

Only solution I found is to store a mirrored version of the column I

2条回答
  •  感情败类
    2020-12-31 19:27

    A index over reverse field will be the solution, some think like:

    create index idx_reverse on table ( reverse( field ) );
    select * from table where reverse(field) like 'txet%';
    

    but MySQL don't alow index over expressions, only over columns:

    this is MySQL create index syntax:

    CREATE [UNIQUE|FULLTEXT|SPATIAL] INDEX index_name
        [index_type]
        ON tbl_name (index_col_name,...)
        [index_option] ...
    

    This is postgres create index syntax:

    CREATE [ UNIQUE ] INDEX [ CONCURRENTLY ] name ON table [ USING method ]
        ( { column | ( expression ) } [ opclass ] [, ...] )
        ...
    

    A work around may be create indexed second field (field -> dleif) and a mysql trigger to keep reversed field:

    alter table my_table add column dleif ...;
    create index idx_reverse on my_table ( dleif );
    Create Trigger `reverse_field` Before Update on `my_table` for each row BEGIN
        set new.dleif = reverse( new.field );
    END;
    select * from table where dleif like reverse('%text');
    

提交回复
热议问题