This question already has an answer here:
I have two table categories
and posts
, I don't want to get all records for each category. I want to get limited rows from each category.
categories
table as below :-
- ID
- Name
- Slug
posts
table as below :-
- ID [ PK ]
- title
- slug
- content
- category [Key - Foreign key]
- publish_date
What i am trying to achieve is , I want to get 10 records from posts
for each category
.
What i am doing at the moment is so dangerous, that it runs lots of query, i want to minimize it to 1 query.
<?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.
}
?>
can i have some "inner join
" query, which can reduce my query to 1-2 query and get me same results as above one ?
I want to have 10 articles for each category to be fetched. In future, i may have 40-45 category, and for each category , on an average, i may have 80-90 posts. While fetching all posts for 40-45 category from above method, can take my application on coaster ride. So i need some feasible method, where i can limit my posts record for each 40-45 category.
This is not simple inner join, where i am fetching posts, but this is actually limiting the inner join records to display for each parent table.
</div>