MySQL - 在JOIN中的给定日期之前选择最新记录

时间:2013-02-20 03:33:36

标签: mysql sql date join

请耐心等待,我是SQL的新手,我在解释这个问题时遇到了麻烦...

我有两个类似于以下的表:

test1
+------+----------+----------+-----------+
|  id  |  serial  |  t1data  |  t1date   |
+------+----------+----------+-----------+
|  1   |    a     |   ...    |  6/02/12  |
|  2   |    a     |   ...    |  6/04/12  |
|  3   |    b     |   ...    |  6/06/12  |
|  4   |    a     |   ...    |  6/08/12  |
+------+----------+----------+-----------+

test2
+------+----------+----------+-----------+
|  id  |  serial  |  t2data  |  t2date   |
+------+----------+----------+-----------+
|  1   |    a     |   ...    |  6/05/12  |
|  2   |    b     |   ...    |  6/07/12  |
|  3   |    b     |   ...    |  6/08/12  |
|  4   |    a     |   ...    |  6/09/12  |
+------+----------+----------+-----------+

我想创建一个查询来加入这两个表,以便test2中的每条记录都对应于test1日期之前发生的最新test2记录。任何给定的序列都可以在任一表中有多个记录。

使用上面的示例,结果应如下所示:

+----------+----------+-----------+----------+-----------+
|  serial  |  t2data  |  t2date   |  t1data  |  t1date   |
+----------+----------+-----------+----------+-----------+
|    a     |   ...    |  6/05/12  |   ...    |  6/04/12  |
|    b     |   ...    |  6/07/12  |   ...    |  6/06/12  |
|    b     |   ...    |  6/08/12  |   ...    |  6/06/12  |
|    a     |   ...    |  6/09/12  |   ...    |  6/08/12  |
+----------+----------+-----------+----------+-----------+

这是我尝试的查询,但它不起作用。

SELECT 
    t2.serial, t2.t2data, t2.t2date, t1a.t1data, t1a.t1date
FROM 
    test2 t2
JOIN 
    test1 t1a ON (t1a.serial = t2.serial AND t1a.t1date > t2.t2date)
LEFT JOIN 
    test1 t1b ON (t1a.serial = t1b.serial AND t1a.t1date < t1b.t1date)
WHERE 
    t1b.serial IS NULL

我可能会犯这个错误,但我能做些什么才能使这项工作成功?

1 个答案:

答案 0 :(得分:0)

我不确定这是否是最好的方法,但它有效:

SELECT t2.serial, t2.t2data, t1.t1data, t1.t1date
FROM
  (SELECT t2.serial, t2.t2data, t2.t2date,
         (SELECT max(t1date)
            FROM test1 t1
           WHERE t1.serial = t2.serial
             AND t1.t1date <= t2.t2date) AS t1date
  FROM test2 t2) t2
  LEFT OUTER JOIN
   test1 t1 ON t2.serial = t1.serial AND t2.t1date = t1.t1date;

http://www.sqlfiddle.com/#!2/215c263/2