mysql从每个id中随机选择一行

n3schb8v  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(354)

我的数据库中有一个表,它有两列: id 以及 color . 每个 id 可能有多个具有不同值的行 color . 例如:

id     color
--------------
1      black
1      white
1      green
2      yellow
3      red
3      black

我只想为每一行选择一行 id ,但是随机的。我已经尝试使用两个select查询,但它总是返回每个id的第一行。有什么问题?!

SELECT * FROM (SELECT * FROM collections ORDER BY RAND()) AS a
GROUP BY id
yebdmbv4

yebdmbv41#

您可以尝试:

select t.*
from t
where t.color = (select t2.color
                 from t t2
                 where t2.id = t.id
                 order by rand()
                 limit 1
                );

为了提高性能,可以在 (id, color) .
你的代码应该根本不起作用。它使用 select *group by --意味着你有未聚合的列。这应该是一个编译时错误。
编辑:
哈哈。当然,上面有个问题。为每一行调用子查询,使每一行都有机会进入结果集中。叹气。有时代码并不是我想要它做的。一种解决方案是给随机数生成器播种。这是“任意的”,但不是“随机的”--每次运行都会得到相同的值:

select t.*
from t
where t.color = (select t2.color
                 from t t2
                 where t2.id = t.id
                 order by rand(concat(t2.id, t2.color))
                 limit 1
                );

如果你没有太多的颜色,你可以使用 group_concat() 技巧:

select t.id,
       substring_index(group_concat(color order by rand()), ',', 1)
from tA quick and dirty solution is to seed the random number generator:
group by id;

相关问题