mysql - 如何从 mySQL 表中为每个 user_id 获取 2 个随机行?

标签 mysql

我有一个表,其中包含来自不同 user_id 的许多产品。像这样:

product_id | user_id
01           20
02           20
03           20
04           20
05           32
06           32
07           53
08           53
09           53
10           84
11           84
etc.

我试图为每个不同的 user_id 获取恰好 2 行,随机排序。

我得到的最接近的是这个查询:

SELECT * FROM db_products ORDER BY user_id, RAND() 

但这让我的每一行都随机排序,而不是每个 user_id 随机排序 2 行。

我尝试了 LIMIT 2 但总共只显示 2 行。实现这一目标的最简单方法是什么?

非常感谢您的帮助:)

最佳答案

最简单的方法可能是使用变量:

select p.*
from (select p.*,
             (@rn := if(@u = user_id, @rn + 1,
                        if(@u := user_id, 1, 1)
                       )
             ) as rn
      from db_products p cross join
           (select @u := 0, @rn := 0) params
      order by user_id, rand()
     ) p
where rn <= 2;

还有其他可能性。如果您的字符串不太可能溢出并且您希望产品位于单行上:

select user_id,
       substring_index(group_concat(product_id order by rand(), ',', 2)
from db_products
group by user_id;

关于mysql - 如何从 mySQL 表中为每个 user_id 获取 2 个随机行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32790511/

相关文章:

MySQL : Using a function output with IN

php - Linux 和 Php : server with MySQL database with terminal

php - 数组到字符串的转换(使用 json_encode 方法时出现 SQL 错误)

java - 使用Mysql ClusterJ jar文件连接到NDB集群

mysql - SUM 结果的子查询 AVG

mysql - MySQL查询的ORDER BY和GROUP BY

Mysql LIKE %...% 连同表

python - MySQL返回的数据类型和python为不同的函数输出不同的类型

mysql - 在 MySQL 中循环遍历枚举

php - PHP Mysql 根据列对结果进行分组统计