好的,假设我有以下表格:
配方
id (pk)
name
added
modified
recipe_versions
id (pk)
recipe_id (fk to recipes.id)
version
content
added
我想要的是一个查询,它抓取最新的recipe_versions.added
数据,然后加入基础recipe
数据。然后按recipes.added ASC
对所有结果进行排序我有以下内容,但是group by,没有选择最新的recipe_versions行,似乎是选择第一行。
SELECT r.`id`,
r.name,
rv.version,
rv.content,
r.added,
r.modified,
FROM recipes r,
recipe_versions rv
WHERE r.`id` = rv.recipe
GROUP BY rv.recipe
HAVING max(rv.added)
ORDER BY r.added ASC
答案 0 :(得分:2)
使用此解决方案:
SELECT
c.*, b.*
FROM
(
SELECT recipe_id, MAX(added) AS mostrecent
FROM recipe_versions
GROUP BY recipe_id
) a
INNER JOIN
recipe_versions b ON
a.recipe_id = b.recipe_id AND
a.mostrecent = b.added
INNER JOIN
recipes c ON a.recipe_id = c.id
ORDER BY
c.added