2013-03-11 61 views
0

我需要爲DB中的每個家庭獲取最新的歷史記錄項目(來自某個類別 - 1422)。 我看見幾個例子左右,而來到這個查詢:Mysql - 獲取每個家庭的最新歷史記錄

SELECT *, MAX(created_at) 
FROM family_histories 
WHERE family_history_cat_id = 1422 
GROUP BY family_id 

是好?

+2

你將需要提供比這更多的信息!例如你的模式,一些示例數據,預期的輸出.... – ManseUK 2013-03-11 11:46:59

回答

0

您可以使用INNER JOIN也得到MAX ID爲每個組

SELECT 
    fh.* 
FROM family_histories 
    INNER JOIN (SELECT 
     family_history_cat_id, 
     MAX(created_at) 
      FROM family_histories 
      GROUP BY family_id) AS l 
    ON l.family_history_cat_id = fh.family_history_cat_id 
WHERE fh.family_history_cat_id = 1422 
0

嘗試

SELECT * 
FROM family_histories 
WHERE family_history_cat_id = 1422 
GROUP BY family_id 
ORDER BY created_at DESC 
LIMIT 1