每个类别的帖子限制 10 条记录

Limit 10 records from posts for each category

我有两个 table categoriesposts,我不想获取每个类别的所有记录。我想从每个类别中获取有限的行。

categories table 如下:-

  1. ID
  2. 姓名
  3. 鼻涕虫

posts table 如下:-

  1. ID [PK]
  2. 标题
  3. 鼻涕虫
  4. 内容
  5. 类别[键-外键]
  6. publish_date

我想要实现的是,我想从 posts 中为每个 category.

获取 10 条记录

我现在正在做的事情非常危险,它运行了很多查询,我想将它最小化为 1 个查询。

<?php

    $fetchCat = $mysqli->query("SELECT * from categories");
    while($row = $fetchCat->fetch_assoc()) {
        $fetchPost = $mysqli->query("SELECT id, title, slug from posts where category=".$mysqli->real_escape_string($row['id'])." limit 10");
        // Processing my code.
    }
?>

我可以有一些“inner join”查询吗,它可以将我的查询减少到 1-2 个查询并得到与上面一个相同的结果?

我想为每个类别提取 10 篇文章。将来,我可能有 40-45 个类别,对于每个类别,平均而言,我可能有 80-90 个帖子。从上述方法获取 40-45 类别的所有帖子时,可以让我的应用程序坐上过山车。所以我需要一些可行的方法,我可以限制我的帖子记录为每个 40-45 个类别。

这不是简单的内部连接,我在这里获取帖子,但这实际上限制了内部连接记录以显示每个 parent table.

我终于在2个查询中找到了解决方案。几乎没有改善。

第一个查询,我 运行 用于类别并将它们存储在数组中。

$cat_array = array();
$fetchCat = $mysqli->query("SELECT * from categories");
while($rowCat = $fetchCat->fetch_assoc()) {
   // Category processing....
}

第二个查询,我 运行 针对 post 使用 group_concatSUBSTRING_INDEX 获取每个类别的 10 条记录。

$post_array = array();
$fetchPost = $mysqli->query("select category, 
             SUBSTRING_INDEX(group_concat(id), ',', 10) as post_id, 
             SUBSTRING_INDEX(group_concat(title), ',', 10) as post_title, 
             SUBSTRING_INDEX(group_concat(slug), ',', 10) as post_slug from posts 
             group by category;");

while($rowPost = $fetchPost->fetch_assoc()) {
    $post_array[ $rowPost['category'] ] [id] = $rowPost['post_id'];
    $post_array[ $rowPost['category'] ] [title] = $rowPost['post_title'];
    $post_array[ $rowPost['category'] ] [slug] = $rowPost['post_slug'];
}

2条查询和所有需要的数据[categoriestable条数据,每个类别10条poststable条数据]

我不得不为 post_idpost_titlepost_slug 做一些爆炸并在我的应用程序中使用它。

现在,要获取任何类别的所有标题和 slug 的列表,这很简单,例如,对于类别 ID“1”,我所要做的就是 :-

$post_array[1][id]  // Returns all post_id associated with category 1.

非常感谢@billynoah,为我指明 "group wise" 方向,"AsConfused" 完成我的查询并让我知道,还有命令 analyze table posts

谢谢