SQL INDEX not used on WHERE ABS(x-y) < k condition, but used on y - k < x < y + k condition

前端 未结 2 1791
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-16 05:03

I have a query involving couples of rows which have a less-than-2-hours time-difference (~0.08333 days):

SELECT mt1.*, mt2.* FROM mytable mt1, mytable mt2 
          


        
2条回答
  •  一向
    一向 (楼主)
    2021-01-16 05:18

    I believe that the inclusion of AND is the reasoning as per :

    The WHERE clause on a query is broken up into "terms" where each term is separated from the others by an AND operator. If the WHERE clause is composed of constraints separate by the OR operator then the entire clause is considered to be a single "term" to which the OR-clause optimization is applied.

    The SQLite Query Optimizer Overview

    It may be worthwhile running ANALYZE to see if that improves matters.

    As per the comment:

    I think the previously added paragraph can clarify why ABS(x-y) < k is not using index, and why x < y + k is using it, don't you think so? Would you want to include this paragraph? [All terms of the WHERE clause are analyzed to see if they can be satisfied using indices. To be usable by an index a term must be of one of the following forms: column = expression, column IS expression, column > expression ...

    The following has been added.

    To be usable by an index a term must be of one of the following forms:
    column = expression
    column IS expression
    column > expression
    column >= expression
    column < expression
    column <= expression
    expression = column
    expression > column
    expression >= column
    expression < column
    expression <= column
    column IN (expression-list)
    column IN (subquery)
    column IS NULL

    I'm not sure if it would work with a BETWEEN (e.g. WHERE column BETWEEN expr1 AND expr2).

提交回复
热议问题