mysql - 有一个左连接,其中涉及第二个表中的重复项 - 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
但这不起作用。
解决方案
您可以加入过滤最新时间戳的相关子查询:
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
此处(您的示例数据并未证明这一点)。
推荐阅读
- plsql - 为什么 to_char() 总是将分钟转换为 07?
- vba - 某些事件不会为组合框触发
- javascript - 如何使用javascript正确破坏地图函数中的对象?
- php - Edit json item by id
- r - Rserver 中的 RStudio,禁用 ShinyApp 上的空闲超时
- unity3d - 未添加 _Stencil 属性时的 Unity 着色器警告
- r - 删除只有零的行
- javascript - 不变量失败:您不应该使用
外面 - ckan - CKAN Datastore Create 不起作用,action/datastore_create 说“内部错误”
- c# - runsettings.xml 文件不适用于 dotnet 测试覆盖率命令