我目前有 2 个表一些呼叫信息。第一个表包含与用户列表连接的呼叫列表,第二个表包含登录注销信息。
我必须将状态列(如下所示(添加到第一个表中,拉出用户最后一个 logTable.xtime 小于 table1.time 的位置
基本上是"此用户在此呼叫之前的最后状态是什么"。
调用表
callID userID time
1 15 xx:xx
1 16 xx:xx
2 15 xx:xx
2 16 xx:xx
日志表
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
由于我在注释点没有第一个表中的时间值,因此无法相应地过滤该表。
在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)
上的索引。