IshaS
IshaS

Reputation: 837

mysql retrive data giving limit and sub limit

I have a table named item with category ID and item IDs. Item ID is the primary key and each item is related to category ID.

I want to retrieve 20 items, but 4 items for one category. If there aren't 4 items for some category, then select all items from this category.

This is my query, it is not working:

SELECT * FROM `item`
JOIN (SELECT `item_id` FROM `item` GROUP BY `category_id` LIMIT 4) LIMIT 20;

my table stucture

item

item id     |   category id
----------------------------
1           |   1
2           |   1
3           |   2
4           |   2
5           |   1
6           |   3

if my table has

category

category    |   count(item)
-----------------------------
1           |   5
2           |   3
3           |   10
4           |   8   
5           |   12
6           |   6
7           |   6
8           |   6

I want to select 20 items like that category items from this category

----------
1   |   4
2   |   3
3   |   4
4   |   4
5   |   4
6   |   1

Upvotes: 0

Views: 145

Answers (1)

Muhammad Raheel
Muhammad Raheel

Reputation: 19882

You can try this query

SET @level = 0;
SET @group = '';
SELECT 
    item_id,
    category_id
FROM (
    SELECT 
        item_id,
        category_id,
        @level := IF(@group = category_id, @level+1, 1) AS level, 
        @group := category_id as EGroup 
    FROM item
    ORDER BY category_id 
) rs
WHERE level < 5 

Here is some sample data

| ID | ITEM_ID | CATEGORY_ID |
|----|---------|-------------|
|  1 |       1 |           1 |
|  2 |       2 |           1 |
|  3 |       3 |           1 |
|  4 |       4 |           1 |
|  5 |       5 |           1 |
|  6 |       6 |           2 |
|  7 |       7 |           2 |
|  8 |       8 |           2 |
|  9 |       9 |           2 |
| 10 |      10 |           3 |
| 11 |      11 |           3 |
| 12 |      12 |           3 |
| 13 |      13 |           3 |
| 14 |      14 |           3 |
| 15 |      15 |           3 |
| 16 |      16 |           4 |
| 17 |      17 |           4 |
| 18 |      18 |           5 |
| 19 |      19 |           5 |
| 20 |      20 |           5 |
| 21 |      21 |           5 |
| 22 |      22 |           5 |
| 23 |      23 |           6 |
| 24 |      24 |           7 |
| 25 |      25 |           7 |

Output

| ITEM_ID | CATEGORY_ID |
|---------|-------------|
|       1 |           1 |
|       2 |           1 |
|       3 |           1 |
|       4 |           1 |
|       9 |           2 |
|       8 |           2 |
|       7 |           2 |
|       6 |           2 |
|      15 |           3 |
|      14 |           3 |
|      13 |           3 |
|      12 |           3 |
|      16 |           4 |
|      17 |           4 |
|      22 |           5 |
|      21 |           5 |
|      20 |           5 |
|      19 |           5 |
|      23 |           6 |
|      24 |           7 |
|      25 |           7 |           

SQL Fiddle Demo

Upvotes: 2

Related Questions