mysql - 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 的随机行
解决方案
每个播放列表需要 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
推荐阅读
- scala - 运行 spark-submit 的问题:java.lang.NoSuchMethodError: com.couchbase.spark.streaming.Mutation.key()
- javascript - 多个过滤器一起工作。将多个过滤器类型匹配在一起
- python - 如何使用嵌套序列化程序我收到属性错误
- javascript - Promise.all 导致 Jest 显示 UnhandledPromiseRejectionWarning
- python - 使用 XPath 在内部属性中接收数据
- tensorflow - 将神经网络拆分为 2 个微服务
- python - 如何使用 Graph API 和用户令牌抓取 Facebook 数据?
- python - 理解模块/包的问题
- r - 在 R Shiny with Leaflet 中选择多个过滤器选项的问题
- laravel - Laravel 路由组问题(空白页)