I have the following tables:
TABLE product
id int(11)
title varchar(400)
TABLE tag
id int(11)
text varchar(100)
TABLE product_tag_map
product_id int(11)
tag_id int(11)
PRODUCT_TAG_MAP maps tags to product. The distribution of tags in the system isn't normal, i.e., some tags have much more products than others.
I'm trying to write an SQL that will fetch 25 random products: 5 products per tag, for 5 tags (so that's 5x5 = 25).
Found an answer here: How can I get an even distribution using WHERE id IN(1,2,3,4)
But this doesn't yield random products - it always fetches the same products per tag.
Here is the SQL I have:
SET @last_tag = 0;
SET @count_tag = 0;
SELECT DISTINCT id FROM (
SELECT
product.*,
@count_tag := IF(@last_tag = product_tag_map.tag_id, @count_tag, 0) + 1 AS tag_row_number,
@last_tag := product_tag_map.tag_id
FROM product
LEFT JOIN product_tag_map ON (product_tag_map.product_id=product.id)
WHERE
product_tag_map.tag_id IN (245,255,259,281,296)
) AS subquery WHERE tag_row_number <= 5;
How do I make it return random products per tag?
Any help would be much appreciated! Thanks.