From http://www.penglixun.com/tech/database/mysql_virtual_function_index.html
SQL statements for function compute with columnsMySQL cannot use indexes. MySQL does not have function indexes in Oracle,
For example:
SELECT * FROM table_1 WHERE func_1(col_1) < const_1 AND func_2(col_2) = const_2 ORDER BY func_1(col_1); |
In Oracle, we can build a Composite Function Index:
CREATE INDEX idx_1 ON table_1 ( func_2(col_2), func_1(col_1)); |
But in MySQL, function indexes are not provided. What should I do? Stop now? If such a requirement exists, we have to solve it. We want to use redundancy + triggers to create a virtual function index.
First, use the new columns to store the function compute results, add col_1_f1 and col_2_f2 columns to store the function compute results of col_1/col_2 respectively, and then write two triggers, insert and update operations are performed respectively.
CREATE TRIGGER trg_f1 BEFORE UPDATE ON verycd FOR EACH ROW BEGIN SET NEW.col_1_f1=func_1(NEW.col_1); SET NEW.col_2_f2=func_2(NEW.col_2); END; CREATE TRIGGER trg_f1 BEFORE INSERT ON verycd FOR EACH ROW BEGIN SET NEW.col_1_f1=func_1(NEW.col_1); SET NEW.col_2_f2=func_2(NEW.col_2); END; |
Then we create an index for the two columns col_1_f1 and col_2_f2:
CREATE INDEX idx_1 ON table_1 ( col_2_f2,col_1_f1 ); |
Change the query statement:
SELECT * FROM table_1 WHERE col_1_f1 < const_1 AND col_2_f2 = const_2 ORDER BY col_1_f1; |
This achieves a virtual "Function Index". From this perspective, the implementation of the function index is not complex, mySQL only needs to record the results of function compute in B-tree as the creation keyword. Why not mysql?