1
I have 3 tables, products, Category, product_categories, this last one was created pq the product and category relation is n to n. I have a select that returns me all products of all categories, but I wanted to return me only 10 products of each category
This is my select:
select "products".*, "product_categories"."idCategory" as "idCategory"
from "products"
inner join "product_categories" on "products"."id" = "product_categories"."idProduct"
where "product_categories"."idCategory" in (5,4,10,7)
If the limit
placed at the end of the query is returned only the first 10 products and their respective categories
And I’ve also thought about doing several consultations, one for each category, but that would be very long compared to what I have
Just out of curiosity, how would this be for MS SQL SERVER?
– PauloHDSousa
Something like this: CREATE TABLE TEST ( ID VARCHAR(100), PRODUCT VARCHAR(100), VARCHAR(100) ) INSERT INTO TEST VALUES (1, 'APPLE', 'FRUIT') INSERT INTO TEST VALUES (2, 'PEAR', 'FRUIT') INSERT INTO TEST VALUES (3, 'CARROT', 'VEG') INSERT INTO TEST VALUES (4, 'BEET', 'VEG') INSERT INTO TEST VALUES (5, 'BANANA', 'FRUIT') INSERT INTO TEST VALUES (6, 'ABOBORA', 'VEG') SELECT CATEGORIA, PRODUCT FROM ( SELECT ROW_NUMBER() OVER(PARTITION BY CATEGORY ORDER BY CATEGORY) AS QTD, PRODUCT, CATEGORY FROM TEST GROUP BY CATEGORIA, PRODUCT ) AS X WHERE QTD <= 2
– Pedro Costa
Interesting, thank you very much.
– PauloHDSousa
I put it on JS Fidle to make it formatted: https://jsfiddle.net/n253oLda/
– Pedro Costa
I’ve tested it here in a local bank, it works fine, I’ve never needed anything like it, but if I ever need it, I’ll thank you
– PauloHDSousa
It worked, thank you very much!!! And the best thing is that this query takes as long as the one I was using, very good
– Nono Player