简体   繁体   中英

Fetch category wise data from database table with limit

I am trying to fetch 2 rows of each category from a single table where I have category also mentioned. When I try to fetch data using GROUP BY Clause, I am able to get 1 row for each type of category, but I want two rows. How can I achieve that result.

For example

| id | name | category |

| 1 | orange | fruits |

| 2 | mango | fruits |

| 3 | cherry | fruits |

| 4 | potato | veggie |

| 5 | onion | veggie |

| 6 | pumpkin | veggie |

| 7 | basil | herbs |

| 8 | black pepper | herbs |

| 9 | cloves | herbs |

Table example image, please check

I want to fetch first two rows of each category.

Since my mysql version is 5.7, I cannot use window commands as suggested in the answer, though it may be correct, but not for my version.

Edit: With solution which is posted by @jared.

Solution to the problem

Issue resolved.

I think window functions is what you want here:

-- Asuming your table is named 'food'
SELECT * FROM ( 
    SELECT 
        *, 
        ROW_NUMBER() OVER(PARTITION BY category) AS category_row_index 
    FROM `food` 
) food_catgorized 
    WHERE 
        food_catgorized.category_row_index BETWEEN 1 AND 2;

UPD: following query should work with MySql 5.7:

-- Asuming your table is named 'food'
SELECT food.* FROM food 
JOIN ( 
    SELECT category, GROUP_CONCAT(id) AS ids
        FROM `food` 
        GROUP BY category
) category_ids
ON 
    food.category = category_ids.category
WHERE 
    FIND_IN_SET(food.id, category_ids.ids) BETWEEN 1 AND 2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM