gpt4 book ai didi

mysql - 在涉及第二个表中的重复项时有一个左连接 - MYSQL

转载 作者:行者123 更新时间:2023-11-29 15:22:16 25 4
gpt4 key购买 nike

表 1:

user  score  
------------
A 1
B 2

表 2:

    user   comment    time
----------------------------
A good <timestamp 1>
A bad <timestamp 2>
B average <timestamp 3>

我想连接这两个表,以便得到以下内容:

    user   score  comment
-------------------------
A 1 good
B 2 average

如您所见,我需要根据时间戳(最近的时间戳)加入第二个表的注释。我试过了

SELECT st.user as user,st.score,
case when v.comment is null then 'NA' else v.comment end as comment
FROM tale1
left JOIN (select distinct user,comment,max(time) from table2) v ON st.user=v.user

但这不起作用。

最佳答案

您可以加入根据最新时间戳进行过滤的相关子查询:

select 
t1.*,
t2.comment
from table1 t1
left join table2 t2
on t2.user = t1.user
and t2.time = (
select max(t22.time)
from table2 t22
where t21.user = t1.user
)

旁注:我不确定您是否需要此处的左连接(您的示例数据未证明这一点)。

关于mysql - 在涉及第二个表中的重复项时有一个左连接 - MYSQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59308867/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com