SQL 查询以获取数据库中 table 的所有帖子,但最多来自特定用户的 5 个条目?

SQL query to get all posts from a table in the db but max 5 entrys from a specific user?

我正在构建一个 php 博客系统,并希望在起始页上显示每个用户的所有帖子,但最多五个。 我想通过数据库中的查询来做到这一点,但我不知道该怎么做。 我想 count() 函数会派上用场,但有人可以帮我吗

这是我今天的功能,我只是想改进它以从每个用户那里获得最多五个帖子

protected function getAllPostsDB() {
    $sql = "SELECT recipes.Recipe_ID, recipes.Title, recipes.Short_description, recipes.Step_by_step, 
    recipes.create_date, recipes.last_mod_date, recipes.Portions, recipes.imgPath, users.Username
    FROM recipes 
    JOIN users
        ON recipes.User_ID = users.User_ID
    ORDER BY recipes.create_date DESC";
    $stmt = $this->connect()->query($sql);
    /* fetch all is already set to associative array*/
    $result = $stmt->fetchAll();
    return $result;`

如果你是运行 MySQL 8.0,只需使用window函数:

SELECT r.Recipe_ID, r.Title, r.Short_description, r.Step_by_step, 
    r.create_date, r.last_mod_date, r.Portions, r.imgPath, u.Username
FROM (
    SELECT r.*, ROW_NUMBER() OVER(PARTITION BY User_ID ORDER BY create_date DESC) rn
    FROM recipes r
) r
INNER JOIN users ON r.User_ID = u.User_ID
WHERE r.rn <= 5
ORDER BY r.create_date DESC

这给出了每个用户的最后五个食谱,如第 create_date 列所指定。如果您需要其他排序规则,可以将 ROW_NUMBER()ORDER BY 子句更改为其他列或列集。