mysql-select 来自每个 id 的随机行
mysql-select a random row from each id
我的数据库中有一个 table,它有 2 列:id
和 color
。每个 id
可能有多个行,其中 color
的值不同。例如:
id color
--------------
1 black
1 white
1 green
2 yellow
3 red
3 black
我想 select 每个 id
只有一行,但随机。我已经尝试使用两个 select 查询,但它总是 returns 每个 id 的第一行。有什么问题吗?!
SELECT * FROM (SELECT * FROM collections ORDER BY RAND()) AS a
GROUP BY id
你可以试试:
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
——这意味着您有未聚合的列。那应该是一个编译时错误。
编辑:
哈哈。当然,上面有一个问题。为每一行调用子查询,使每一行都有机会出现在结果集中。叹。有时代码不做我想让它做的事。一种解决方案是为随机数生成器播种。这是 "arbitrary" 但不是 "random" -- 您将在每个 运行:
上获得相同的值
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;
我的数据库中有一个 table,它有 2 列:id
和 color
。每个 id
可能有多个行,其中 color
的值不同。例如:
id color
--------------
1 black
1 white
1 green
2 yellow
3 red
3 black
我想 select 每个 id
只有一行,但随机。我已经尝试使用两个 select 查询,但它总是 returns 每个 id 的第一行。有什么问题吗?!
SELECT * FROM (SELECT * FROM collections ORDER BY RAND()) AS a
GROUP BY id
你可以试试:
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
——这意味着您有未聚合的列。那应该是一个编译时错误。
编辑:
哈哈。当然,上面有一个问题。为每一行调用子查询,使每一行都有机会出现在结果集中。叹。有时代码不做我想让它做的事。一种解决方案是为随机数生成器播种。这是 "arbitrary" 但不是 "random" -- 您将在每个 运行:
上获得相同的值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;