【问题标题】:Limit 10 records from posts for each category [duplicate]每个类别的帖子限制 10 条记录[重复]
【发布时间】:2015-08-14 09:53:35
【问题描述】:

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

categories 表格如下:-

  1. 身份证
  2. 姓名
  3. 蛞蝓

posts 表格如下:-

  1. ID [PK]
  2. 标题
  3. 蛞蝓
  4. 内容
  5. 类别 [键 - 外键]
  6. 发布日期

我想要实现的是,我想从 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 类别的帖子记录。

这不是简单的内部联接,我在其中获取帖子,但这实际上限制了内部联接记录以显示每个父表。

【问题讨论】:

  • 你关心你得到哪 10 只给定的猫 4 只。是否在 slug 列上建立索引?每个 tbl 有多少行
  • 你有几类?
  • @Ala 我有大约 12-14 个类别。
  • @AsConfused ,我希望每个类别有 10 条记录。
  • 搜索“mysql groupwise limit”。看这里:stackoverflow.com/questions/2129693/…

标签: php mysql sql join inner-join


【解决方案1】:

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

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

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

第二个查询,我使用group_concatSUBSTRING_INDEX对post进行了查询,以获取每个类别的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

谢谢

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-09-15
    • 1970-01-01
    • 2013-02-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-10
    • 1970-01-01
    • 2019-09-06
    相关资源
    最近更新 更多