具有左连接,其中涉及第二个表中的重复项-MYSQL

问题描述 投票:0回答:2

表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

但是这不起作用。

mysql sql greatest-n-per-group
2个回答
0
投票
您可以加入相关的子查询以对最新的时间戳进行过滤:

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 )


0
投票
您只想要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;

© www.soinside.com 2019 - 2024. All rights reserved.