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

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

    So, I dont have enough data to be sure of the run time. This will only work if column P is unique? In order to get two indexes working, I created two indexes and the following query...

    Index A - FirstX, P, Y, Z
    Index B - P, LastX
    

    This is the query

    select A.P, A.Y, A.Z 
    from 
        (select P, Y, Z from asdf A where A.firstx <= 185000 ) A
        join 
        (select P from asdf A where A.LastX >= 185000 ) B
        ON A.P = B.P
    

    For some reason this seemed faster than

    select A.P, A.Y, A.Z 
    from asdf A join asdf B on A.P = B.P
    where A.firstx <= 185000 and B.LastX >= 185000
    

提交回复
热议问题