表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
)
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;