检索最近的记录

时间:2012-01-18 22:31:59

标签: mysql

我有一点mysql查询脑冻结。我需要从表中检索最新记录,按第二列分组。像这样:

SELECT ca.id, ca.activity_date, cat.contact_id as cid
FROM activity ca
JOIN activity_target cat
  ON ca.id = cat.activity_id
WHERE ca.activity_type_id = 44
GROUP BY cid
ORDER BY activity_date DESC

...除了我需要最近的记录(使用activity_date)组中(在组之后执行的顺序)。我尝试使用HAVING activity_date = max(activity_date),但这不起作用。

2 个答案:

答案 0 :(得分:1)

我认为你可以这样做:

SELECT ca.id, ca.activity_date, cat.contact_id as cid
FROM activity ca
JOIN activity_target cat
  ON ca.id = cat.activity_id
WHERE ca.activity_type_id = 44
    and ca.id = (SELECT id from activity a
            join activity_target t on a.id = t.activity_id
        WHERE t.contact_id = cat.contact_id
        ORDER BY activity_date DESC LIMIT 1)
ORDER BY activity_date DESC

如果没有查看您的架构,我无法肯定地说,我猜测MySQL和Microsoft SQL Server之间存在差异。

答案 1 :(得分:0)

SELECT ca.id, ca.activity_date, cat.contact_id AS cid
FROM activity ca
  JOIN activity_target cat
    ON ca.id = cat.activity_id
  JOIN 
      ( SELECT t.contact_id
             , MAX(a.activity_date) AS activity_date 
        FROM activity a
          JOIN activity_target t 
            ON a.id = t.activity_id
        WHERE a.activity_type_id = 44
        GROUP BY t.contact_id 
      ) AS grp
    ON  grp.contact_id = cat.contact_id
    AND grp.activity_date = ca.activity_date
WHERE ca.activity_type_id = 44
ORDER BY ca.activity_date DESC