首页 > 解决方案 > 如果没有足够的行,则 rand() 的 SQL 顺序会使用重复项填充结果

问题描述

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

表:主题烹饪只有 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

标签: mysqlsqlrandomduplicatessql-order-by

解决方案


这可能在应用程序中做得更好。但是,如果必须,您可以将行数相乘,然后排序和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 行。


推荐阅读