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

后端 未结 12 1332
盖世英雄少女心
盖世英雄少女心 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条回答
  •  广开言路
    2021-01-11 17:10

    Another approach is to precalculate the solutions, if that number isn't too big.

    CREATE TABLE SomeTableLookUp (
        X INT NOT NULL
        PrimaryKeyCol BIGINT NOT NULL,
        PRIMARY KEY(X, PrimaryKeyCol)
    );
    

    And now you just pre-populate your constant table.

    INSERT INTO SomeTableLookUp
    SELECT X, PrimaryKeyCol
    FROM SomeTable
    JOIN (
       SELECT DISTINCT X FROM SomeTable 
    ) XS
    WHERE XS.X BETWEEN StartX AND EndX 
    

    And now you can SELECT your answers directly.

    SELECT SomeTable.*
    FROM SomeTableLookup
    JOIN SomeTable
    ON SomeTableLookup.PrimaryKeyCol = SomeTable.PrimaryKeyCol
    WHERE SomeTableLookup = ?
    LIMIT 10
    

提交回复
热议问题