Mysql 使用Max函数分组时如何包含多个未聚合列
我仍然是SQL查询的学习者,我已经检查了一些类似的问题,但无法根据我的问题进行思考 请找出放在Sql小提琴中的结果 基本上,我正在尝试创建一个输出Mysql 使用Max函数分组时如何包含多个未聚合列,mysql,Mysql,我仍然是SQL查询的学习者,我已经检查了一些类似的问题,但无法根据我的问题进行思考 请找出放在Sql小提琴中的结果 基本上,我正在尝试创建一个输出 id sales_lead_id comments contact_type time_spent next_contact_date contact_situation employee_id date created_at updated_at 2651 1 rrrrrrrrrrrrrrrrr
id sales_lead_id comments contact_type time_spent next_contact_date contact_situation employee_id date created_at updated_at
2651 1 rrrrrrrrrrrrrrrrr 0 3 2019-12-22 1 5 2019-12-21 2019-12-21T16:49:00Z 2019-12-22T18:05:37Z
2652 2 gggggggggggggg 0 17 2019-12-22 0 5 2019-12-19 2019-12-19T13:11:50Z 2019-12-22T18:15:59Z
我知道如何使用Max(update_at)获取最近编辑的行,但是
我无法在sql中放入其他列(即id、注释、联系人类型等),我不理解如何将此值传递到主sql中以获得上述完整结果
任何帮助都会很感激的,在这个问题上坚持了很长时间
Sql完整表
select * from sales_lead_followup;
输出
id sales_lead_id comments contact_type time_spent next_contact_date contact_situation employee_id date created_at updated_at
1 1 dddddddddddddddddddddd 0 0 (null) 0 5 2019-05-18 2019-05-18T09:12:57Z 2019-05-18T09:12:57Z
2 2 dddddddddddd 0 0 (null) 0 5 2019-05-26 2019-05-26T06:32:56Z 2019-05-26T06:32:56Z
2651 1 rrrrrrrrrrrrrrrrr 0 3 2019-12-22 1 5 2019-12-21 2019-12-21T16:49:00Z 2019-12-22T18:05:37Z
2652 2 gggggggggggggg 0 17 2019-12-22 0 5 2019-12-19 2019-12-19T13:11:50Z 2019-12-22T18:15:59Z
1511 1 rrrrrr 0 6 2019-11-19 1 5 2019-11-17 2019-11-17T18:31:40Z 2019-11-19T18:30:07Z
1512 2 ggggggggggggg 0 2 2019-11-19 1 5 2019-11-17 2019-11-17T18:38:29Z 2019-11-19T18:38:23Z
SQL获取最近添加的销售线索id行
select sales_lead_id , max(updated_at) from sales_lead_followup group by sales_lead_id ;
输出:-
sales_lead_id max(updated_at)
1 2019-12-22T18:05:37Z
2 2019-12-22T18:15:59Z
现在,我将介绍如何在上面的SQL中添加额外的列以创建以下输出
id sales_lead_id comments contact_type time_spent next_contact_date contact_situation employee_id date created_at updated_at
2651 1 rrrrrrrrrrrrrrrrr 0 3 2019-12-22 1 5 2019-12-21 2019-12-21T16:49:00Z 2019-12-22T18:05:37Z
2652 2 gggggggggggggg 0 17 2019-12-22 0 5 2019-12-19 2019-12-19T13:11:50Z 2019-12-22T18:15:59Z
您可以在“主”查询的IN条件中使用聚合查询的输出: 不过,如果列表中的查询越来越大(只有几条记录,这是非常合理的),那么该查询可能会失控。相反,您可以考虑使用一个相关的子查询,这将更快得多,尤其是关于<代码> SaluxDeLyID ID/代码>的索引:
select *
from sales_lead_followup t1
WHERE updated_at =
(
select max(updated_at)
from sales_lead_followup
WHERE sales_lead_id = t1.sales_lead_id
group by sales_lead_id
);
select *
from sales_lead_followup t1
WHERE updated_at =
(
select max(updated_at)
from sales_lead_followup
WHERE sales_lead_id = t1.sales_lead_id
group by sales_lead_id
);