0

我需要为数据库中的每个家庭获取最新的历史项目(来自某个类别 - 1422)。我看到了几个例子,并来到了这个查询:

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

好吗?

4

2 回答 2

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
于 2013-03-11T11:47:37.353 回答
0

尝试

SELECT *
FROM family_histories
WHERE family_history_cat_id = 1422
GROUP BY family_id
ORDER BY created_at DESC
LIMIT 1
于 2013-03-11T11:48:08.093 回答