1

好的,所以假设我有以下表格:

食谱

id (pk)
name
added
modified

食谱版本

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
4

1 回答 1

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
于 2012-07-08T06:25:57.980 回答