首页 > 解决方案 > 有一个左连接,其中涉及第二个表中的重复项 - MYSQL

问题描述

表格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

但这不起作用。

标签: mysqlsqlgreatest-n-per-group

解决方案


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

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
    )

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


推荐阅读