SELECT STRAIGHT_JOIN t.*
FROM (SELECT @r:=0, @c:= null) AS rownum_init,
(SELECT *, (@r:=IF(@c=shop_categoryID, @r+1, 1)) AS rownum, (@c:=shop_categoryID)
FROM t_shop
ORDER BY shop_categoryID, RAND()) AS t
WHERE t.rownum <= 5;
下面是在我的測試輸出上的MySQL 30年5月5日,使用您的測試數據:
+---------+-----------------+--------+-----------------------+
| shop_id | shop_categoryID | rownum | (@c:=shop_categoryID) |
+---------+-----------------+--------+-----------------------+
| 5 | 1 | 3 | 1 |
| 1 | 1 | 1 | 1 |
| 9 | 1 | 5 | 1 |
| 2 | 1 | 2 | 1 |
| 7 | 1 | 4 | 1 |
| 22 | 2 | 3 | 2 |
| 23 | 2 | 4 | 2 |
| 25 | 2 | 5 | 2 |
| 13 | 2 | 1 | 2 |
| 15 | 2 | 2 | 2 |
+---------+-----------------+--------+-----------------------+
通常約涉及ORDER BY ... RAND()
任何解決方案的建議是,它是不可伸縮的,而且隨着你的表的大小變得更昂貴。但是對於像你所描述的那樣複雜的隨機選擇問題,它可能是解決問題的唯一方法。如果表現不佳,請不要感到驚訝。
回覆您的評論:
我不明白你的意思。 Rownum在每個類別中有1個獨特的值,然後隨着類別的變化從1開始。
向我們展示您到目前爲止所嘗試的內容(即您所查詢的查詢)。 – gkalpak
SELECT * FROM( \t SELECT * \t FROM t_shop \t ORDER BY RAND() )AS T GROUP BY shop_CategoryID ORDER BY shop_CategoryID –
SELECT * FROM t_shop草皮 WHERE shop_categoryID IN ( SELECT shop_categoryID FROM t_shop WHERE shop_id = sod.shop_id ORDER BY shop_categoryID limit 5 ) –