Indexing column with REPLACE function in mySQL

拈花ヽ惹草 提交于 2019-12-12 03:54:29

问题


May be a silly question to ask.

I need to use this a lot in both join and where:

REPLACE(table_a.column_1, '-', '') = REPLACE(table_b.column_2, '-', '')

since bit data inconsistency from other companies' system

Is that possible or any other database type can have index of a column with REPLACE function? eg:

ALTER TABLE `table_a` ADD INDEX ( REPLACE(`column_1`, '-', '') ) ;

Database Type: MyISAM


回答1:


There is no such thing as computed column in MySQL.

If you want to format some value to speed-up index search, you will probably have to use some trigger. As a matter of fact, I answered almost the same question this morning: see https://stackoverflow.com/a/18047511/2363712 for a similar example.

In your case, that would lead to something like that:

CREATE TABLE `table_a`(`column_1` VARCHAR(255), ... ,
                       `column_1_fmt` VARCHAR(255),
                       INDEX(`column_1_fmt`));

CREATE TRIGGER ins_table_a BEFORE INSERT ON `table_a`
FOR EACH ROW
    SET NEW.`column_1_fmt` = REPLACE(NEW.column_1, '-', '');

CREATE TRIGGER upd_table_a BEFORE UPDATE ON `table_a`
FOR EACH ROW
    SET NEW.`column_1_fmt` = REPLACE(NEW.column_1, '-', '');

Now you will use column_1_fmt to search for values/join on values having the required format.


Concerning your special need (removing dashes -- from some kind of serial/reference number?). Maybe you should reverse the problem. Store those value as canonical form (no dash). And add required dashes at SELECT time.



来源:https://stackoverflow.com/questions/18053385/indexing-column-with-replace-function-in-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!