A SQL query searching for rows that satisfy Column1 <= X <= Column2 is very slow

后端 未结 12 1400
盖世英雄少女心
盖世英雄少女心 2021-01-11 16:27

I am using a MySQL DB, and have the following table:

CREATE TABLE SomeTable (
  PrimaryKeyCol BIGINT(20) NOT NULL,
  A BIGINT(20) NOT NULL,
  FirstX INT(11) N         


        
12条回答
  •  梦毁少年i
    2021-01-11 16:59

    It seems that the only way to make the query fast is to reduce the number of fetched and compared fields. Here is the idea.

    We can declare a new indexed field (for instance UNSIGNED BIGINT) and store both values FistX and LastX in it using an offset for one of the fields.

    For example:

    FirstX     LastX      CombinedX
    100000     500000     100000500000
    150000     220000     150000220000
    180000     190000     180000190000
    550000     660000     550000660000   
    70000      90000      070000090000 
    75         85         000075000085
    

    an alternative is to declare the field as DECIMAL and store FirstX + LastX / MAX(LastX) in it. Later look for the values satisfying the conditions comparing the values with a single field CombinedX.

    APPENDED

    And then you can fetch the rows checking only one field: by something like where param1=160000

    SELECT * FROM new_table 
    WHERE
    (CombinedX <= 160000*1000000) AND
    (CombinedX % 1000000 >= 160000);
    

    Here I assume that for all FistX < LastX. Of course, you can calculate the param1*offset in advance and store it in a variable against which the further comparisons will be done. Of course, you can consider not decimal offsets but bitwise shifts instead. Decimal offsets were chosen as they are easier to read by a human to show in the sample.

提交回复
热议问题