2013-03-11 112 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