我有两个表categories和posts,我不想得到每个类别的所有记录。我想从每个类别中得到有限的行。
categories表如下:-
posts表如下:-
我想要实现的是,我想从posts获得10张category的记录。
我目前正在做的事情是如此危险,以至于它运行了大量的查询,我想将它最小化为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个类别。
这不是简单的内部连接,我在这里获取帖子,但这实际上限制了每个父表的内部连接记录的显示。
发布于 2015-06-01 07:30:08
我终于在2查询中找到了解决方案。几乎没有什么改善。
第一个查询,我运行类别并将它们存储在一个数组中。
$cat_array = array();
$fetchCat = $mysqli->query("SELECT * from categories");
while($rowCat = $fetchCat->fetch_assoc()) {
// Category processing....
}第二个查询,我遇到post,使用group_concat和SUBSTRING_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_id、post_title、post_slug做一些爆炸,并在我的应用程序中使用它。
现在,为任何类别获取所有标题和片段的列表,这很简单,例如,对于id“1”类,我所要做的就是:-
$post_array[1][id] // Returns all post_id associated with category 1.非常感谢@billynoah为我指明了“分组智能”方向,"AsConfused“通过我的查询并告诉我,还有命令analyze table posts。
谢谢
https://stackoverflow.com/questions/30565021
复制相似问题