Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
516 views
in Technique[技术] by (71.8m points)

mysql leftjoin ,一对多,如何关联到右表最新的记录

假设有数据表user, user_login,
user表,

iduid
11001
21002

user_login表

iduidcontent
11001数据1
21002数据2
31001数据3
41001数据4
51002数据5

现在将user表当主表,左连接查询login表,
select * from user as t1 left join (select max(id),content group by uid)
这样查到的结果uid 和content 对不上,也就是会随机选择一个值,

像这种情况想要根据主表的uid,不同的uid匹配关联表中uid相等的最新一条记录该如何做。

这个表字段等都是随手写的,不用考虑太多,只是能不能通过只通过sql语句查出来


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

这种情况,join 两次就好了:

select
from user as t1 
left join
(
    select max
    (
        id
    ) as max_id,
    uid
    from user_login group by uid
) as t2 on t1.uid=t2.uid 
left join
(
    select id,
    content
    from user_login
) as t3 on t2.max_id=t3.id

结果
image

参见线上的演示:
https://bixuebihui.com/sql/gr...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...