I have a table product_category
, with fields id
, name
, parent_id
and level
.
For example, the category Agriculture has id = 75
, level = 1
and parent_id = NULL
. The subcategories Corn, Wheat, Rye, etc. have level = 2
and parent_id = 75
.
In my site I'd like to show the top-level categories and below each of them, only 5 subcategories. But doing a query to retrieve them it's harder than what I thought.
If I do the following query:
SELECT a.name, a.parent_id FROM product_category a
WHERE (
SELECT b.level
FROM product_category b
WHERE b.id = a.parent_id
LIMIT 1
) = 1
I retrieve all top-level categories and subcategories, but there are thousands of subcategories so it would be very unnecessarily expensive when I only want the first 5 of each.
If I do the following one:
SELECT a.name, a.parent_id FROM product_category a
WHERE (
SELECT b.level
FROM product_category b
WHERE b.id = a.parent_id
LIMIT 1
) = 1
LIMIT 5
It only retrieves 5 subcategories, not 5 subcategories per top-level category.
Then I thought of doing it the following way:
(
SELECT a.name, a.parent_id FROM product_category a
WHERE parent_id = 12
LIMIT 5
) UNION (
SELECT a.name, a.parent_id FROM product_category a
WHERE parent_id = 21
LIMIT 5
) UNION (
SELECT a.name, a.parent_id FROM product_category a
WHERE parent_id = 75
LIMIT 5
) UNION (
.
.
.
Which looks very dirty and hard-coded, yet it is the only way I can think of right now. Is there any other solution to this?
Thanks!