Sql 使用另一个表中的最大值联接表
我目前有2个表,其中包含一些通话信息。 第一个表包含与用户列表连接的呼叫列表,第二个表包含登录注销信息 我必须将下面所示的状态列添加到第一个表中,在用户最后一个logTable.xtime小于table1.time的位置拉入 基本上是“此用户在此呼叫之前的最后状态是什么” 可呼叫 日志表 我设法为所有用户提取last xtime,但由于我没有第一个表的时间,它返回最新状态。但是如果我盲目地加入表格,它就会变成一张乱七八糟的表格Sql 使用另一个表中的最大值联接表,sql,postgresql,Sql,Postgresql,我目前有2个表,其中包含一些通话信息。 第一个表包含与用户列表连接的呼叫列表,第二个表包含登录注销信息 我必须将下面所示的状态列添加到第一个表中,在用户最后一个logTable.xtime小于table1.time的位置拉入 基本上是“此用户在此呼叫之前的最后状态是什么” 可呼叫 日志表 我设法为所有用户提取last xtime,但由于我没有第一个表的时间,它返回最新状态。但是如果我盲目地加入表格,它就会变成一张乱七八糟的表格 select q2.uid, q2.xtime,q3.status
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;
这可以利用logTableuserId上的索引time desc.谢谢,实际上我从未听说过这个关键字。现在我们将更深入地研究它。
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
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;