Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/postgresql/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 连接两个表并仅保留第一个最近的事件_Sql_Postgresql_Join_Greatest N Per Group - Fatal编程技术网

Sql 连接两个表并仅保留第一个最近的事件

Sql 连接两个表并仅保留第一个最近的事件,sql,postgresql,join,greatest-n-per-group,Sql,Postgresql,Join,Greatest N Per Group,我目前有以下表格: table_1 id | timestamp | origin | info table_2 id | timestamp | origin | type 我的目标是为表2中的每一行找到表1中的原始事件。我只想保留第一个。 例如: table 1 1 | 1000 | "o1" | "i1" 2 | 2000 | "o2" | "i2" 3 | 2010 | "o2" | "i2" table 2 1 | 1010 | "o1" | "t1" 2 | 2100 | "o

我目前有以下表格:

table_1
id | timestamp | origin | info

table_2
id | timestamp | origin | type
我的目标是为表2中的每一行找到表1中的原始事件。我只想保留第一个。 例如:

table 1
1 | 1000 | "o1" | "i1"
2 | 2000 | "o2" | "i2"
3 | 2010 | "o2" | "i2"

table 2
1 | 1010 | "o1" | "t1"
2 | 2100 | "o2" | "t2"
我的预期结果是:

table_2.id | table_2.timestamp | table_2.origin | table_2.type | table_1.info | table_1.timestamp
1          | 1010              | "o1"           | "t1"         | "i1"         | 1000
2          | 2100              | "o2"           | "t2"         | "i2"         | 2010
目前,我只是在
origin
table_2.timestamp>table_1.timestamp
上使用一个简单的连接,它提供了:

table_2.id | table_2.timestamp | table_2.origin | table_2.type | table_1.info | table_1.timestamp
1          | 1010              | "o1"           | "t1"         | "i1"         | 1000
2          | 2100              | "o2"           | "t2"         | "i2"         | 2000
2          | 2100              | "o2"           | "t2"         | "i2"         | 2010
正如你们所看到的,我不想要上面的第二行,因为我只想要表1中第一个最近的事件


有什么想法吗?

跨数据库解决方案是使用相关子查询连接和过滤:

select 
    t2.*,
    t1.info,
    t1.timestamp t1_timestamp
from 
    table_2 t2
    inner join table_1 t1
        on t1.origin = t2.origin
        and t1.timestamp = (
            select max(t11.timestamp) 
            from table_1 t11
            where t11.origin = t2.origin and t11.timestamp < t2.timestamp
        )
order by t2.id
-两个查询都会产生:

id | timestamp | origin | type | info | t1_timestamp -: | --------: | :----- | :--- | :--- | -----------: 1 | 1010 | o1 | t1 | i1 | 1000 2 | 2100 | o2 | t2 | i2 | 2010 id |时间戳|来源|类型|信息| t1 |时间戳 -: | --------: | :----- | :--- | :--- | -----------: 1 | 1010 | o1 | t1 | i1 | 1000 2010年2 | 2100 | o2 | t2 | i2
感谢您的回答和Db Fiddle的发现。 id | timestamp | origin | type | info | t1_timestamp -: | --------: | :----- | :--- | :--- | -----------: 1 | 1010 | o1 | t1 | i1 | 1000 2 | 2100 | o2 | t2 | i2 | 2010