I'm searching for the best method to get result with database contain more than 100000 Post and more than 100000 Cat
Here is my tables
Cats
-----------------
- id | name |
-----------------
- 1 | x |
-----------------
- 2 | y |
-----------------
Post
--------------------------------------
- id | cat_id | title | content |
--------------------------------------
- 1 | 1 | Post 1 | .. . . .|
--------------------------------------
- 2 | 1 | Post 2 | . . . . .|
--------------------------------------
- 3 | 2 | Post 3 | .. . . .|
--------------------------------------
- 4 | 1 | Post 4 | . . . . .|
--------------------------------------
- 5 | 1 | Post 5 | .. . . .|
--------------------------------------
- 6 | 2 | Post 6 | . . . . .|
--------------------------------------
- 7 | 1 | Post 7 | .. . . .|
--------------------------------------
- 8 | 2 | Post 8 | . . . . .|
--------------------------------------
Here's the Result I want to get
Result
--------------------------------------
-Postid | cat_id | title | content |
--------------------------------------
- 1 | 1 | Post 1 | .. . . .|
--------------------------------------
- 2 | 1 | Post 2 | . . . . .|
--------------------------------------
- 3 | 2 | Post 3 | .. . . .|
--------------------------------------
- 6 | 2 | Post 4 | . . . . .|
--------------------------------------
Here is Query I Just Write , But i look for Best query
SELECT
*
From
post
WHERE posts.cat_id = 1 limit 2
UNION
SELECT
*
From
post
WHERE posts.cat_id = 2 limit 2
What Happen if i want to get from 10 cats in one query
set @i := 0, @cat_id = 0;
select
post.id as Postid,
cat_id,
title,
content
from
post
inner join (
select
id,
case
when @cat_id = cat_id then @i := @i + 1
else @i := 1
end as i,
case when @cat_id != cat_id then @cat_id := cat_id end
from (
select id, cat_id
from post
-- where cat_id in (1, 2) uncomment this to limit categories
order by cat_id
) a
) s on s.id = post.id
where i <= 2
order by cat_id, post.id
The question title says every category and the question says 10 categories so I commented the where clause to make it optional.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With