SQL Query to Join Two Tables Based Off Closest Timestamp

后端 未结 3 1943
眼角桃花
眼角桃花 2020-12-16 12:41

I have two tables in SQL and I need to be able to do a join based off of the timestamp in table B that is earlier than or equal to the timestamp in table A.

So, here

相关标签:
3条回答
  • 2020-12-16 13:22
    SELECT case.id, case.resolution, case.timestamp, class.value
      FROM closed_cases AS case
      LEFT JOIN classifications AS class 
      ON case.timestamp >= class.timestamp
      WHERE case.timestamp BETWEEN $1 AND $2;
    
    0 讨论(0)
  • 2020-12-16 13:23

    change the time stamp and use an int as a key to connect the tables. this will work much faster then comparing date

    table 1 field1 field2 field3 ConnectorField

    table2 field1 field2 field3 ConnectorField

    and all you need to do is select * from table1 T1 inner join table2 T2 on T1.ConnectorField = T2.ConnectorField

    0 讨论(0)
  • 2020-12-16 13:24

    If you can make changes to the table structures, I recommend changing the classification table to include an end date as well as a start date - it will be much easier to join to the table that way.

    If not, I suggest the following:

    SELECT case.id, case.resolution, case.timestamp, class.value
      FROM closed_cases AS case
      LEFT JOIN (select c.*, 
                        (select min(timestamp)
                         from classifications c1
                          where c1.timestamp > c.timestamp) timeend
                 from classifications c) AS class 
      ON case.timestamp >= class.timestamp and 
         (case.timestamp < class.timeend or class.timeend IS NULL)
      WHERE case.timestamp BETWEEN $1 AND $2;
    

    EDIT - with the end date on classification:

    SELECT case.id, case.resolution, case.timestamp, class.value
      FROM closed_cases AS case
      LEFT JOIN classifications AS class 
      ON case.timestamp >= class.timestamp and case.timestamp < class.timeend
      WHERE case.timestamp BETWEEN $1 AND $2;
    
    0 讨论(0)
提交回复
热议问题