我想在分组后随机化我的数据。我如何才能以优雅的方式实现这一点?
我在这里创建了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/