Sql: Optimizing BETWEEN clause

前端 未结 9 756
孤街浪徒
孤街浪徒 2021-02-06 07:38

I wrote a statement that takes almost an hour to run so I am asking help so I can get to do this faster. So here we go:

I am making an inner join of two tables :

<
9条回答
  •  情深已故
    2021-02-06 08:04

    You're pretty much going to get most of the rows from both tables in this case, plus you've got a sort.

    The question is, does the calling process really need all the rows, or just the first few? This would change how I'd go about optimising the query.

    I'll assume your calling process wants ALL the rows. Since the join predicate is not on an equality, I'd say a MERGE JOIN may be the best approach to aim for. A merge join requires its data sources to be sorted, so if we can avoid a sort the query should run as fast as it possibly can (barring more interesting approaches such as specialised indexes or materialized views).

    To avoid the SORT operations on intervals and measures, you could add indexes on (measures.time,measures.measure) and (intervals.entry_time, intervals.exit_time). The database can use the index to avoid a sort, and it'll be faster because it doesn't have to visit any table blocks.

    Alternatively, if you only have an index on measures.time, the query may still run ok without adding another big index - it'll run slower though because it'll probably have to read many table blocks to get the measures.measure for the SELECT clause.

提交回复
热议问题