我有一个数据库,希望为每个User_ID
选择10个随机行。
到目前为止,我已经有了这段代码,但是我不确定如何为每个User_ID
值选择10个随机行。
SELECT User_ID
FROM Database
ORDER BY RAND()
LIMIT 10
GROUP BY User_ID
答案 0 :(得分:0)
在8.0之前的MySQL中,这很痛苦。这是一种方法:
select d.*
from (select d.*,
(@rn := if(@u = user_id, @rn + 1,
if(@u := user_id, 1, 1)
)
) as rn
from (select d.* from database d order by user_id, rand()
) d cross join
(select @u := 0, @rn := 0) params
) d
where rn <= 10;