在表 X 中,有一个字段 Y(int),它保存从 1 到 8 的值。 我正在尝试找到最有效的方法来创建查询(这是存储过程的一部分),该查询可以从数据库中随机选择 5 条记录。
整个表中的 5 条记录不是随机的 - 例如,该过程应该能够 选择 1 个随机记录,其中 Y=1,另外 2 个记录,其中 Y=2,另外 2 个记录,其中 Y 在 (4,5,6) 中。
有推荐的方法来实现它还是我应该使用 Union? 此查询需要尽可能快。
最佳答案
联盟应该是最快的方法
(select * from your_table where Y = 1 order by rand() limit 1)
union
(select * from your_table where Y = 2 order by rand() limit 2)
union
(select * from your_table where Y in (4,5,6) order by rand() limit 2)
关于mysql - 从mysql中选择随机记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24975093/