Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mysql: get 2 result from every cat [one to many relation ship]

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

like image 534
Mona Abdelmajeed Avatar asked Sep 25 '12 11:09

Mona Abdelmajeed


1 Answers

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.

like image 78
Clodoaldo Neto Avatar answered Nov 09 '22 17:11

Clodoaldo Neto