如何仅获取最近加入的配对?

时间:2019-07-09 13:14:22

标签: sql oracle oracle11g

我有两个表,第二个表通过多个条目(1:n)连接到第一个表。

第一个表具有id_something(另一个表,但目前不重要)和每天date_day的条目。

+-----------+
| Table ONE |
+----+------+-------+----------+----------+
| id | id_something | date_day | created  |
+----+--------------+----------+----------+
|  1 |          666 | 2019-1-1 | 2019-1-1 |
|  2 |          666 | 2019-1-1 | 2019-7-7 |
|  3 |          123 | 2019-1-1 | 2019-1-1 |
+----+--------------+----------+----------+

第二个表与此id连接,并包含键值对。

+-----------+
| Table TWO |
+--------+--+--+-----+
| id_one | foo | bar |
+--------+-----+-----+
|      1 |   1 |  20 |
|      1 |   2 |  21 |
|      2 |   1 |  30 |
|      2 |   2 |  31 |
|      2 |   3 |  32 |
|      3 |   1 |  10 |
+--------+-----+-----+

我想查询所有可能的连接,很简单,这是一个JOIN:

SELECT *
FROM one
LEFT JOIN two
ON two.id_one = one.id;

+----+--------------+----------+----------+--------+-----+-----+
| id | id_something | date_day | created  | id_one | foo | bar |
+----+--------------+----------+----------+--------+-----+-----+
|  1 |          666 | 2019-1-1 | 2019-1-1 |      1 |   1 |  20 |
|  1 |          666 | 2019-1-1 | 2019-1-1 |      1 |   2 |  21 |
|  2 |          666 | 2019-1-1 | 2019-7-7 |      2 |   1 |  30 |
|  2 |          666 | 2019-1-1 | 2019-7-7 |      2 |   2 |  31 |
|  2 |          666 | 2019-1-1 | 2019-7-7 |      2 |   3 |  32 |
|  3 |          123 | 2019-1-1 | 2019-1-1 |      3 |   1 |  10 |
+----+--------------+----------+----------+--------+-----+-----+

现在,如您所见,我还有一个created字段。 id_somethingdate_day可能是相同的-但我只想与第二张表具有最新的(created DESC)对。

因此,在这种情况下,查询应返回:

+----+--------------+----------+----------+--------+-----+-----+
| id | id_something | date_day | created  | id_one | foo | bar |
+----+--------------+----------+----------+--------+-----+-----+
|  2 |          666 | 2019-1-1 | 2019-7-7 |      2 |   1 |  30 |
|  2 |          666 | 2019-1-1 | 2019-7-7 |      2 |   2 |  31 |
|  2 |          666 | 2019-1-1 | 2019-7-7 |      2 |   3 |  32 |
|  3 |          123 | 2019-1-1 | 2019-1-1 |      3 |   1 |  10 |
+----+--------------+----------+----------+--------+-----+-----+

但是我无法使其工作...我试图使用DISTINCT甚至子查询和case构造,但是它要么不起作用,要么非常。分组依据也不会返回每个加入的对,而对于表一中的每个id仅返回一行。

要实现理想的结果,我缺少什么?

(如果不使用特定于Oracle的synthax,那将是一个奖励。)

2 个答案:

答案 0 :(得分:1)

您可以使用分析功能:

SELECT *
FROM (SELECT o.* ROW_NUMBER() OVER (PARTITION BY id ORDER BY created DESC) as seqnum
      FROM one o
     ) o LEFT JOIN
     two t
     ON t.id_one = o.id
WHERE o.seqnum = 1;

答案 1 :(得分:1)

使用row_number()获取最新的id_something,然后使用加入

select a.*,b.* from     
(
select *,
row_number()over(partition by id_something order by created desc) rn  from one
) a join two b ON b.id_one = a.id;
 where rn=1