我有一行产品,我想获得10条随机记录,但每个user_id最多只有1行。现在我有这个:
SELECT user_id, product_id, price, name, category, is_featured
FROM db_products
WHERE category!=15 AND active=1 AND deleted=0 AND is_featured=1
ORDER BY RAND() DESC LIMIT 0,12
我尝试过SELECT DISTINCT user_id, ...
,但这不起作用。该表有100个产品,每个user_id可能有多个,但我想检索每个user_id最多1个,但仍然总共10个。
在没有更复杂的结构的情况下,这有可能吗?
答案 0 :(得分:3)
我可能遗漏了一些东西,但你尝试过做GROUP BY吗?
SELECT user_id, product_id, price, name, category, is_featured
FROM db_products
WHERE category!=15 AND active=1 AND deleted=0 AND is_featured=1
GROUP BY user_id -- SPECIFY FIELD HERE
ORDER BY RAND() DESC
LIMIT 0,12
这将为每个用户分组一行,或者您希望分组的字段。
答案 1 :(得分:2)
在子查询中随机排序后,尝试在主查询中进行分组:
SELECT * FROM
(SELECT user_id, product_id, price, name, category, is_featured
FROM db_products
WHERE category!=15 AND active=1 AND deleted=0 AND is_featured=1
ORDER BY RAND()) AS subquery
GROUP BY user_id
LIMIT 0,10