mysql - 分组后的随机数据

标签 mysql sql random group-by

我想在分组后随机化我的数据。我如何才能以优雅的方式实现这一点?

我在这里创建了SQLFiddle Demo .

预期结果,

金牌、金牌 2、金牌 3、银牌 3、银牌、铜牌

金牌 2、金牌 3、金牌、银牌、银牌 3、铜牌

金牌、金牌 3、金牌 2、银牌、银牌 3、铜牌

铜牌、银牌 3、银牌、金牌 2、金牌、金牌 3 等....

简而言之,它应该首先按字母顺序(名称)对它们进行分组,然后在内部随机分组数据

我试过了,

SELECT * FROM type ORDER BY name, RAND()

这会按名称排序,但不会随机化。

SELECT * FROM type GROUP BY name ORDER BY RAND()

这会随机化数据但不会对它们进行分组。

最佳答案

使用substring_index(col, ' ', 1)用单个空格分隔符拆分字符串值并获取第一个标记并将其用作您的第一个订单标准。在您的二阶标准上使用 rand() 以便随机分配第一个单词相同的名称

select name
from type
order by substring_index(name, ' ', 1), rand()

这里的假设是您姓名列中的单词始终由单个空格分隔

编辑
以下是有关 substring_index 的更多示例:

select substring_index('hello world', ' ', 1); -- 'hello'
select substring_index('hello', ' ', 1); -- 'hello'
select substring_index('hello_world foo', ' ', 1); -- 'hello_world'
select substring_index('yippie ki yay', ' ', 2); -- 'yippie ki'

关于mysql - 分组后的随机数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24256572/

相关文章:

mysql - 使用 MySQL IN 子句返回所有记录,包括重复项

python - MySQL-Python 代码将 `' 添加到数据库名称

mysql - SQL CONTAINS 在全文索引列上没有返回结果?

MySQL - 错误代码 1054 - where 子句中的未知列 al.article_id

c# - SQL 插入 : Duplicate Key Value Specified?

php - 重复时总结一条记录

mysql - 棘手的 SQL 选择

java - Execute CommandA A% of time, CommandB B% of time, CommandA C% of time ----- Command Z% time 使用随机数

python - 在python中随机化字典

c - 生成随机投票号码