请耐心等待,我是 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
我可能在这一切都错了,但我能做些什么来完成这项工作?