mysql - 如果没有足够的行,则 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
解决方案
这可能在应用程序中做得更好。但是,如果必须,您可以将行数相乘,然后排序和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 行。
推荐阅读
- azure - 在 azure blob 上获取租约一段时间返回 null
- react-native - 多次显示相同项目的平面列表
- php - woocommerce 客户城市将通过“新订单”电子邮件发送
- c++ - 无法在预处理器指令中使用 printf
- html - 如何在不更改其他元素大小的情况下将隐藏元素添加到 flex 父元素?
- bash - sed 仅替换第一次出现,然后仅替换第二次出现,然后仅替换第三次
- haskell - Haskell 工具栈和可执行文件大小
- php - 如果复选框选中已更改,则更改 td 上的类
- amazon-web-services - AWS Workspaces CLI:“开始 - 工作区”的语法
- python - 如何从 Excel 工作表创建嵌套字典并将它们合并在一起