首页 > 解决方案 > Mysql选择具有多个where条件的随机行

问题描述

这是我的表格示例:

id     options     playlist_id
1      ...         7
3      ...         7
4      ...         9
11     ...         9
12     ...         7
14     ...         9

如何为每个 playlist_id 选择(例如)3 个随机行并按 playlist_id 分组结果?

select id, options
from table
where playlist_id = 7 AND playlist_id = 9
group by playlist_id 
ORDER BY RAND()
LIMIT 3

我希望返回 3 个 playlist_id = 7 的随机行和 3 个 playlist_id = 9 的随机行

标签: mysqlsqlrandomgroup-bygreatest-n-per-group

解决方案


每个播放列表需要 3 首随机歌曲。order by并且limit单独无法做到这一点,因为它们对整个结果集进行操作,而您需要以某种方式在每个组内进行洗牌和限制。

假设 MySQL 8.0,可以使用row_number()withorder by rand()子句;这会为共享相同播放列表的记录组中的每条记录分配一个随机排名,然后您可以将其用于过滤:

select id, options
from (
    select 
        t.*, 
        row_number() over(partition by playlis_id order by rand()) rn
    from mytable t
    where playlist_id in (7, 9)
) t
where rn <= 3

推荐阅读