我的数据库中有一个表,它有两列: 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
1条答案
按热度按时间yebdmbv41#
您可以尝试:
为了提高性能,可以在
(id, color)
.你的代码应该根本不起作用。它使用
select *
与group by
--意味着你有未聚合的列。这应该是一个编译时错误。编辑:
哈哈。当然,上面有个问题。为每一行调用子查询,使每一行都有机会进入结果集中。叹气。有时代码并不是我想要它做的。一种解决方案是给随机数生成器播种。这是“任意的”,但不是“随机的”--每次运行都会得到相同的值:
如果你没有太多的颜色,你可以使用
group_concat()
技巧: