【问题标题】:What is the best way to select multiple random results from table with different where cases从具有不同情况的表中选择多个随机结果的最佳方法是什么
【发布时间】:2021-04-27 06:29:52
【问题描述】:

我有这个查询,这没什么特别的,但我认为它根本没有效率。我想从单个表中选择具有不同 where 情况的随机行。因此,结果应该是 1 个随机行,每个选择的特定类型如查询中所示。一些“类型”值可以相同,但它们仍应返回随机结果。

Select * from fruits where type = 1 order by RAND() limit 1
Select * from fruits where type = 1 order by RAND() limit 1
Select * from fruits where type = 3 order by RAND() limit 1
Select * from fruits where type = 4 order by RAND() limit 1
Select * from fruits where type = 4 order by RAND() limit 1

【问题讨论】:

  • 您使用的是哪个 dbms?
  • mysql 但没关系,只要我明白怎么做,即使它不是 mysql 示例
  • 您需要简单地合并查询吗?
  • 不是联合,我只是看不到每次执行 5 个查询有效,所以我只想将其转换为 1 个查询。

标签: mysql sql select sql-order-by


【解决方案1】:

我会这样表达:

select t.*
from (select t.*,
             row_number() over (partition by type order by rand()) as seqnum
      from t 
     ) t join
     (select 1 as type, 2 as n union all
      select 3 as type, 1 as n union all
      select 4 as type, 2 as n
     ) x
     using (type)
where x.n <= seqnum
        

【讨论】:

    【解决方案2】:

    您可以使用ROW_NUMBER() 窗口函数和ORDER BY RAND() 为每个type 的行分配随机排序。
    然后为每个type 选择所需的行数。
    这将在 MySql 中工作:

    SELECT *
    FROM (
      SELECT *, ROW_NUMBER() OVER (PARTITION BY type ORDER BY RAND()) rn 
      FROM fruits 
      WHERE type IN (1, 3, 4)
    ) t
    WHERE rn <= CASE type
      WHEN 1 THEN 2 -- 2 rows for type = 1
      WHEN 3 THEN 1 -- 1 row  for type = 3
      WHEN 4 THEN 2 -- 2 rows for type = 4
    END
    

    查看简化的demo

    【讨论】:

    • 我目前正在使用mysql,但无论如何计划迁移到sql,所以将设置一个测试服务器并在明天测试它,谢谢。
    • @V.Rashkov 对于 SQL Server,唯一的区别是将 RAND() 更改为 NEWID():dbfiddle.uk/…
    【解决方案3】:

    如果您使用的是Postgres

    select distinct on (type) type, *
    from like_this
    where type in ( 1,2,3,4,5)
    order by type, random()
    

    【讨论】:

    • 需要检查如何转换为 mysql,但如果我想返回类似 (1,1,2,3,3,5) 的东西,这只是一个问题。有些结果具有相同的类型,但仍应随机选择?它不会对它们进行分组吗?
    • 不,这是每个类型显示 1 个随机行
    猜你喜欢
    • 1970-01-01
    • 2012-04-20
    • 1970-01-01
    • 1970-01-01
    • 2017-05-08
    • 2017-11-16
    • 2020-12-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多