Create an index using a numeric value in MySQL

Source: Internet
Author: User

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?

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.