我需要为数据库中的每个家庭获取最新的历史项目(来自某个类别 - 1422)。 我看到了几个例子,并提出了这个问题:
SELECT *, MAX(created_at)
FROM family_histories
WHERE family_history_cat_id = 1422
GROUP BY family_id
好吗?
答案 0 :(得分: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
答案 1 :(得分:0)
尝试
SELECT *
FROM family_histories
WHERE family_history_cat_id = 1422
GROUP BY family_id
ORDER BY created_at DESC
LIMIT 1