左联接涉及第二个表中的重复项-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

但这不起作用。

gongshaobo 回答:左联接涉及第二个表中的重复项-MYSQL

您可以与相关的子查询结合使用,该子查询会根据最新的时间戳进行过滤:

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(您的示例数据无法证明这一点)。

,

您只需要table2中的一列,因此我建议使用相关子查询:

select t1.*,(select t2.comment
        from table2 t2
        where t2.user = t1.user
        order by t2.time desc
        limit 1
       ) as comment
from table1 t1;

此查询将最佳利用table2(user,time desc,comment)上的索引-不过,我认为desc在MySQL中会被忽略。

本文链接:https://www.f2er.com/2932580.html

大家都在问