2012-01-18 222 views
0

我有一點的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),但這不起作用。

+0

'contact_id'屬於哪個表? – 2012-01-18 22:47:32

+0

我編輯了指定字段的來源。 – lcdservices 2012-01-18 22:55:33

+0

「activity_target」的主鍵是什麼? – 2012-01-18 23:00:05

回答

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之間的差異。

+0

這是問題的關聯。除非我錯過了一些東西,否則我認爲這隻會讓我陷入同一個漏洞。 – lcdservices 2012-01-18 22:51:04

+0

用相關性編輯。 – Chad 2012-01-18 22:59:15

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