简体   繁体   中英

MySql Limit rows but without truncating group of rows

I have the following table

id| name     |price| groupid | category
---------------------------------------
1 | product1 | 14  | grp1    | apparel
2 | product1 | 16  | grp1    | apparel
3 | product1 | 36  | grp1    | apparel
4 | product2 | 97  | grp2    | apparel
5 | product2 | 87  | grp2    | apparel
6 | product2 | 77  | grp2    | apparel
7 | product3 | 3   | grp3    | apparel
8 | product3 | 2   | grp3    | apparel
9 | product3 | 5   | grp3    | apparel

I want to fetch products in this table by category and group them by group id in app layer. This is the simple SELECT query I am using:

SELECT * FROM products
WHERE category = 'apparel'
LIMIT 0,5

The problem now is the query truncates the result and the last item in grp2 (id=6) is not returned (as one would expect).

I want a query the detects that one item of a group is not returned, fetching that item as well and then truncates the remainder of the result. Basically I want to return all items of a group or no items in a group at all.

How can i possibly achieve this ?

EDIT: each group can potentially have anywhere between 1 to 12 items. It is variable.

Here's one way of doing it:

SELECT t1.*
FROM products AS t1
JOIN (
   SELECT DISTINCT groupid
   FROM (
      SELECT groupid 
      FROM products
      WHERE category = 'apparel'
      LIMIT 0,5) AS t
) AS t2 ON t1.groupid = t2.groupid

The query uses a derived table that contains all distinct groupid values that belong to the rows returned when LIMIT is applied.

Demo here

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