在mysql中选择随机行并限制每个组

时间:2013-12-01 04:29:56

标签: mysql

我无法将12个mysql查询减少到一个调用中。我需要按随机顺序将结果按product_type_id分组,然后将每个组限制为7:

SELECT * FROM products WHERE product_type_id=1 AND deleted='n' ORDER BY RAND() LIMIT 7;
SELECT * FROM products WHERE product_type_id=2 AND deleted='n' ORDER BY RAND() LIMIT 7;
...
SELECT * FROM products WHERE product_type_id=12 AND deleted='n' ORDER BY RAND() LIMIT 7;

目前每个product_type_id(1,2,3,... 12)总共有12个查询。任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:3)

因此,每种产品类型需要7个随机记录(7 * 12条记录)。乍一看,你只是在找工会。

(SELECT * FROM products WHERE product_type_id=1 AND deleted='n' ORDER BY RAND() LIMIT 7)
UNION ALL
(SELECT * FROM products WHERE product_type_id=2 AND deleted='n' ORDER BY RAND() LIMIT 7)
UNION ALL
...
UNION ALL
(SELECT * FROM products WHERE product_type_id=12 AND deleted='n' ORDER BY RAND() LIMIT 7)

如果您需要订购整个结果集,那么您可以在整个ORDER BY之后使用UNION子句。