基于最近时间戳加入两个表的SQL查询

Top*_*gio 16 sql timestamp left-join

我在SQL中有两个表,我需要能够根据表B中的时间戳进行连接,该时间戳早于或等于表A中的时间戳.

所以,这里有两个表的假数据和所需的输出:

封闭案件(表A)

| id | resolution |         timestamp          |
------------------------------------------------
|  1 |     solved | 2006-10-05 11:55:44.888153 |
|  2 |     closed | 2007-10-07 12:34:17.033498 |
|  3 |    trashed | 2008-10-09 08:19:36.983747 |
|  4 |     solved | 2010-10-13 04:28:14.348753 |

分类(表B)


| id |    value    |         timestamp          |
-------------------------------------------------
|  1 |    freshman | 2006-01-01 12:02:44.888153 |
|  2 |   sophomore | 2007-01-01 12:01:19.984333 |
|  3 |      junior | 2008-01-01 12:02:28.746149 |

期望的结果

| id | resolution |         timestamp          |    value    |
--------------------------------------------------------------
|  1 |     solved | 2006-10-05 11:55:44.888153 |    freshman |
|  2 |     closed | 2007-10-07 12:34:17.033498 |   sophomore |
|  3 |    trashed | 2008-10-09 08:19:36.983747 |      junior |
|  4 |     solved | 2010-10-13 04:28:14.348753 |      junior |

所以,我知道的代码需要看起来像下面,我只是无法弄清楚如何处理做ON了的部分JOIN(将要传递的$ 1和$ 2变量):

SELECT case.id, case.resolution, case.timestamp, class.value
  FROM closed_cases AS case
  LEFT JOIN classifications AS class ON ???
  WHERE case.timestamp BETWEEN $1 AND $2;
Run Code Online (Sandbox Code Playgroud)

我知道我可以使用一个子选择,但这将至少运行几千行,可能更多,我需要它真的很快; 所以我希望有一个简单的条款可以做到这一点.

小智 8

如果您可以对表结构进行更改,我建议您更改分类表以包括结束日期和开始日期 - 以这种方式加入表格会更容易.

如果没有,我建议如下:

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;
Run Code Online (Sandbox Code Playgroud)

编辑 - 结束日期分类:

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;
Run Code Online (Sandbox Code Playgroud)