gpt4 book ai didi

Mysql选择具有多个where条件的随机行

转载 作者:行者123 更新时间:2023-12-04 10:19:14 24 4
gpt4 key购买 nike

这是我的表格示例:

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 bylimit单独无法做到这一点,因为它们对整个结果集进行操作,而您不知何故需要在每个组内进行洗牌和限制。

假设 MySQL 8.0,你可以使用 row_number()order 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

关于Mysql选择具有多个where条件的随机行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60940736/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com