【问题标题】:Mysql select random rows with multiple where conditionsMysql选择具有多个where条件的随机行
【发布时间】:2020-07-11 10:09:21
【问题描述】:

这是我的表格示例:

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 的随机行

【问题讨论】:

    标签: mysql sql random group-by greatest-n-per-group


    【解决方案1】:

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

    假设 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
    

    【讨论】:

    • 这比单独查询每个 playlist_id 有效多少?
    • @Toniq:使用单个查询(几乎)总是比使用两个查询更有效:即单次往返服务器,单次查询解析和执行。
    • 使用此查询我仍然收到此错误:在第 5 行靠近 '(PARTITION BY playlist_id ORDER BY RAND()) rn FROM wp_ap_media t'
    • @Toniq:您正在运行哪个版本的 MySQL (select version())?这需要 MySQL 8.0。
    • mysql Ver 15.1 Distrib 10.1.38-MariaDB,适用于 Win64 (AMD64)
    猜你喜欢
    • 2013-11-18
    • 2021-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-16
    相关资源
    最近更新 更多