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

后端 未结 12 1420
盖世英雄少女心
盖世英雄少女心 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:16

    To optimize this query:

    SELECT P, Y, Z FROM SomeTable WHERE FirstX <= ? AND LastX >= ? LIMIT 10;

    Here's 2 resources you can use:

    • descending indexes
    • spatial indexes

    Descending indexes:

    One option is to use an index that is descending on FirstX and ascending on LastX.

    https://dev.mysql.com/doc/refman/8.0/en/descending-indexes.html

    something like:

    CREATE INDEX SomeIndex on SomeTable (FirstX DESC, LastX);

    Conversely, you could create instead the index (LastX, FirstX DESC).

    Spatial indexes:

    Another option is to use a SPATIAL INDEX with (FirstX, LastX). If you think of FirstX and LastX as 2D spatial coordinates, then your search what it does is select the points in a contiguous geographic area delimited by the lines FirstX<=LastX, FirstX>=0, LastX>=X.

    Here's a link on spatial indexes (not specific to MySQL, but with drawings):

    https://docs.microsoft.com/en-us/sql/relational-databases/spatial/spatial-indexes-overview

提交回复
热议问题