为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
弑天下 2023-11-04 21:04:27
我正在构建一个 php 博客系统,希望在起始页上显示每个用户的所有帖子,但最多显示 5 个帖子。我想通过数据库中的查询来做到这一点,但我不知道如何做到这一点。我想 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;`
查看完整描述

1 回答

?
翻过高山走不出你

TA贡献1875条经验 获得超3个赞

如果您运行的是 MySQL 8.0,只需使用窗口函数:


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。如果您需要其他排序规则,可以将ORDER BYof 子句更改为其他列或列集。ROW_NUMBER()


查看完整回答
反对 回复 2023-11-05
  • 1 回答
  • 0 关注
  • 54 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信