Optimize SQL that uses between clause

前端 未结 19 1943
故里飘歌
故里飘歌 2021-01-11 18:03

Consider the following 2 tables:

Table A:
id
event_time

Table B
id
start_time
end_time

Every record in table A is mapped to exactly 1 reco

相关标签:
19条回答
  • 2021-01-11 18:49

    Put an index on B.start_time descending and then use this query:

     SELECT A.id AS idA,
     (SELECT B.id FROM B WHERE A.event_time > B.start_time LIMIT 0, 1
     ORDER BY B.start_time DESC) AS idB
     FROM A
    

    As the time buckets in B are disjoint this would give you the first matching time bucket und you get rid of the between, but still having the sub-query there. Maybe including the B.id in the index would give you some additional small performance boost. (disclaimer: not sure about the MySQL syntax)

    0 讨论(0)
提交回复
热议问题