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

时间:2015-06-01 02:57:52

标签: php mysql sql join inner-join

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

categories表格如下: -

  1. ID
  2. 名称
  3. 蛞蝓
  4. posts表格如下: -

    1. ID [PK]
    2. 标题
    3. 蛞蝓
    4. 含量
    5. 类别[密钥 - 外键]
    6. 出版日期
    7. 我想要实现的目标是,我希望每个postscategory获得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.
          }
      ?>
      

      我可以拥有一些&#34; inner join&#34;查询,这可以减少我的查询到1-2查询,并得到与上面相同的结果吗?

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

      这不是简单的内连接,我提取帖子,但这实际上限制了为每个父表显示的内连接记录。

1 个答案:

答案 0 :(得分:0)

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

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

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

第二次查询,我使用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查询和所有必需数据[categories表数据,每个类别10 posts表数据]

我必须为post_idpost_titlepost_slug进行一些爆炸,并在我的应用程序中使用它。

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

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

非常感谢@billynoah,指出我的“小组明智”方向,“AsConfused”通过我的查询并告诉我,还有命令analyze table posts

由于

相关问题