我无法将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个查询。任何帮助表示赞赏。
答案 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
子句。