我正在構建一個 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()
- 1 回答
- 0 關注
- 130 瀏覽
添加回答
舉報
0/150
提交
取消