用另一个表中的最大值联接一个表

时间:2019-07-17 15:17:57

标签: sql postgresql

我目前有2张桌子一些电话信息。 第一个表包含呼叫列表和用户列表,第二个表包含登录注销信息。

我必须将状态列(如下所示)添加到第一个表中,拉到用户最后一个小于table1.time的logTable.xtime的位置

基本上是“此用户在此呼叫之前的最后状态是什么”。

callTable

callID userID time
1      15     xx:xx
1      16     xx:xx
2      15     xx:xx
2      16     xx:xx

logTable

userID    xtime   status
15        xx:xx    t
15        xx:xx    f
.
.
.
.
16        xx:xx    f
16        xx:xx    t
.
.
.
.

我设法为所有用户拉最后一个xtime,但是由于我没有第一个表的时间,因此它返回最新状态。但是,如果我盲目地加入桌子,它就会变成一团糟。

select q2.uid, q2.xtime,q3.status
from
(select uid,max(xtime) as xtime
from table2

--where xtime<time from table1!!!!!!

group by uid
) q2
left join table2  q3
on q2.uid=q3.uid and q2.xtime=q3.xtime

由于在注释点没有第一张表的时间值,因此无法相应地过滤表。

1 个答案:

答案 0 :(得分:1)

在Postgres中,相对简单的方法是横向联接:

select ct.*, lt.status
from callTable ct left join lateral
     (select lt.*
      from logTable lt
      where lt.userId = ct.userId and lt.time <= ct.time
      order by lt.time desc
      fetch first 1 row only
     ) lt
     on lt.userId = ct.userId;

这可以利用logTable(userId, time desc)上的索引。

相关问题