【问题标题】:SQL order by rand() fill result with duplicates if there's not enough rows如果没有足够的行,则 rand() 的 SQL 顺序会使用重复项填充结果
【发布时间】:2020-12-13 10:38:19
【问题描述】:

我有一个用于在 20,40,60 (LIMIT 20..40..60) 中运行测试的语言锻炼应用程序。 如果 LIMIT 超过所选主题中的行,如何通过重复填充结果?

table:topic Cooking 只有 18 行

假设“从表中选择 topic=Cooking order by rand() LIMIT 40

如何通过重复填充结果,使结果有 40 行,即使没有足够的行数?

table
--------------------------------------
rice
chair
spoon
knife
fork

wanted output - select * order by rand() limit 10
------------------------------------------
chair, rice, spoon, chair, knife, spoon, fork, knife, rice, fork 
-------------------
// forced 10 terms

【问题讨论】:

  • 请显示示例结果以及您希望额外行的外观?

标签: mysql sql random duplicates sql-order-by


【解决方案1】:
    SELECT * FROM
((SELECT *, 1 sortby FROM dictionary where topic='Describing weather' order by rand())
UNION ALL 
(SELECT *, 2 sortby FROM dictionary where topic='Describing weather' order by rand())
)dum 
ORDER BY sortby

【讨论】:

  • 请不要只发布代码作为答案,还要解释您的代码的作用以及它如何解决问题的问题。带有解释的答案通常更有帮助,质量更高,更有可能吸引投票。
【解决方案2】:

这可能在应用程序中做得更好。但如果必须的话,你可以乘以行数,然后排序和limit

select t.*
from t cross join
     (select 1 as n union all select 2 union all select 3 . . . 
      select 40
     ) n
where t.topic = 'Cooking'
order by n.n, rand()
limit 40;

如果您知道您的 where 子句有一定的最小值,您可能不需要临时表中的 40 行。

【讨论】:

  • 这个答案在我看来是对所提问题的合理解释。
猜你喜欢
  • 1970-01-01
  • 2015-11-23
  • 2015-03-20
  • 2021-04-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-06
相关资源
最近更新 更多