简体   繁体   English

在涉及第二个表中的重复项的地方进行左连接 - MYSQL

[英]Have a left join where duplicates in the second table is involved - MYSQL

Table 1:表格1:

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

Table 2:表 2:

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

I want to join these two tables such that I get the below:我想加入这两个表,以便得到以下信息:

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

As you can see I'll need to join the second table's comment based on the timestamp (the most recent timestamp).如您所见,我需要根据时间戳(最近的时间戳)加入第二个表的评论。 I tried我试过

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

but this doesnt work.但这不起作用。

You can join with a correlated subquery that filters on the latest timestamp:您可以加入过滤最新时间戳的相关子查询:

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
    )

Side note: I am unsure that you do need a left join here (your sample data does not demonstrate that).旁注:我不确定您是否需要在此处进行left join (您的示例数据并未证明这一点)。

You only want one column from table2 so I recommend a correlated subquery:您只需要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;

This query will make optimal use of an index on table2(user, time desc, comment) -- alas, though, I think the desc is ignored in MySQL.这个查询将优化使用table2(user, time desc, comment)上的索引——唉,不过,我认为desc在 MySQL 中被忽略了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM