gpt4 book ai didi

mysql - 使用 ORDER BY id DESC 在 Max Date 值上进行 LEFT JOIN

转载 作者:搜寻专家 更新时间:2023-10-30 22:25:55 25 4
gpt4 key购买 nike

假设我有以下两个表:

lead
id(PK) status assigned_to date
1 open Smith 2018-08-26
2 open Drew 2018-08-26
3 new Amit 2018-08-26

lead_comments
id lead_id(FK) comment_data follow_up_time
1 1 old task line2 2018-08-27 14:18:26
2 2 old task line1 2018-08-27 14:18:26
3 1 new task line1 2018-08-27 17:18:00
4 2 new task line3 2018-09-27 20:18:26
5 2 old task line2 2018-08-27 21:18:26

现在,我需要一个 MySQL 查询来选择与最新评论匹配的每个线索(如果存在)Order By latest follow_up_time from lead_comments 表。

我的预期结果:

lead_id comment _id follow_up_time       comment_data    assigned_to    
2 4 2018-09-27 20:18:26 new task line3 Drew
1 3 2018-08-27 17:18:00 new task line1 Smith
3 Null Null Null Amit

我正在尝试:

SELECT l.id as lead_id,
l.status as status,
c.id as comment_id,
c.comment_date as comment_date,
c.comment_data as comment,
c.commented_by,
l.assigned_to
FROM lms_leads l
LEFT JOIN lms_leads_comments as c ON l.id=c.lead_id
JOIN (
SELECT max(cm.id) as id
FROM lms_leads_comments cm
GROUP BY cm.lead_id
) as cc ON c.id=cc.id
GROUP BY l.id
ORDER BY c.follow_up_time DESC

但是,这个查询并没有按照我的预期结果工作

请建议我如何才能实现我想要做的事情?

最佳答案

试试这个(对于 MySQL 版本 < 8.0):

select @rn := 1, @lead_id_lag := 0;

select l.id lead_id,
lc.id comment_id,
lc.follow_up_time,
lc.comment_data,
l.assigned_to
from lead l
left join (
select case when @lead_id_lag = lead_id then @rn := @rn + 1 else @rn := 1 end rn,
@lead_id_lag := lead_id,
id,
follow_up_time,
comment_data,
lead_id
from lead_comments
order by lead_id, follow_up_time desc
) lc on l.id = lc.lead_id and lc.rn = 1;

Demo

关于mysql - 使用 ORDER BY id DESC 在 Max Date 值上进行 LEFT JOIN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52243277/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com