Optimize SQL that uses between clause

前端 未结 19 1940
故里飘歌
故里飘歌 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:24

    You may want to try something like this

    Select A.ID,
    (SELECT B.ID FROM B
    WHERE A.EventTime BETWEEN B.start_time AND B.end_time LIMIT 1) AS B_ID
    FROM A
    

    If you have an index on the Start_Time,End_Time fields for B, then this should work quite well.

    0 讨论(0)
  • 2021-01-11 18:24

    Based on your comment that each entry in A corresponds to exactly one entry in B, the easiest solution would be to remove the AUTOINCREMENT from B's id column, then replace all of B's ids with the ids from A.

    0 讨论(0)
  • 2021-01-11 18:25

    I wouldn't normally recommend a query like this, but...

    Since you've specified that table A only has about 980 rows and that each row maps to exactly one row in table B, then you could do the following and it will most likely be a lot faster than a cartesian join:

    SELECT A.id AS id_from_a,
        (
            SELECT B.id
            FROM B
            WHERE A.event_time BETWEEN B.start_time AND B.end_time
            LIMIT 0, 1
        ) AS id_from_b
    FROM A
    
    0 讨论(0)
  • 2021-01-11 18:25

    By not changing the schema do mean you can't add an index? Try a multi column index on start_time and end_time.

    0 讨论(0)
  • 2021-01-11 18:25

    Give a try using standard comparison operator (< and >).

    0 讨论(0)
  • 2021-01-11 18:30

    Is there an index on B (start_time, end_time)? If not, perhaps adding one might speed up the matching of B rows to A rows?

    Mind you, if you can't change the schema, maybe you can't create new indexes either?

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