MySQL Group by Struggling

时间:2015-07-29 22:40:16

标签: mysql sql group-by sql-order-by

我知道这个问题已经被打死了,我已经彻底研究过,但是没有一个解决方案似乎有效!

我尝试按字段分组,然后按另一个日期字段排序。那么,这就是我必须要开始的事情:

select cm.CreatedDate, cm.Id, cm.CampaignId, cm.ContactId 
from campaignmember as cm 
where cm.ContactId = '0035000002MYN7IAAX';

Query Result 1

现在,我想对这些进行分组,保留具有最近创建日期的行的值。我已经尝试了我在网上看到的所有各种解决方案:

1)我们首先查询和排序的子查询,然后我们有一个外部查询组。它没有用:

select cm.CreatedDate, cm.Id, cm.CampaignId, cm.ContactId 
From (select * from campaignmember as cm  where ContactId = '0035000002MYN7IAAX' order by cm.CreatedDate desc) as cm 
group by cm.ContactId;

Query Result 2

2)使用Max()函数。正如我们所期望的那样,我们得到最大日期,但不是关联的行:

select max(cm.CreatedDate), cm.Id, cm.CampaignId, cm.ContactId 
From  campaignmember as cm 
where cm.ContactId = '0035000002MYN7IAAX';

Query Result 3

3)最后一个建议我可以看到它是如何工作的,但是我们走了:

select max(cm.CreatedDate), cm.Id, cm.CampaignId, cm.ContactId 
From  campaignmember as cm 
where cm.ContactId =  '0035000002MYN7IAAX'group by cm.ContactId 
order by max(cm.CreatedDate) desc;

Query Result 4

这让我感到疯狂(总是如此)。我不会认为这将是困难的......任何建议都会非常,真的很感激!

1 个答案:

答案 0 :(得分:1)

你可以试试这个:

select cm.CreatedDate, cm.Id, cm.CampaignId, cm.ContactId 
from campaignmember as cm where cm.ContactId = '0035000002MYN7IAAX'
and cm.CreatedDate = (select max(c.CreatedDate) from campaignmember c 
                      where c.ContactId = cm.ContactId);

希望帮助你=)