MySQL 获得2%的记录

MySQL get 2% of the record

我正在尝试获取 2% 的随机样本记录。

SELECT * FROM Orders
ORDER BY RAND()
LIMIT (SELECT CEIL(0.02 * (SELECT COUNT(*) FROM Orders)));

由于第 3 行,这个给出了语法错误。我做错了什么吗? 或者有没有更好的方法获取n%的记录?

如果您使用的是 MySQL 8+,那么 ROW_NUMBER() 提供了一个选项:

WITH cte AS (
    SELECT *, ROW_NUMBER() OVER (ORDER BY RAND()) rn,
              COUNT(*) OVER () cnt
    FROM Orders
)

SELECT *
FROM cte
WHERE 1.0*rn / cnt <= 0.02;

在 MySQL 5.7 及更早版本中,我们可以模拟行号:

SELECT *
FROM
(
    SELECT *, (@rn := @rn + 1) AS rn
    FROM Orders, (SELECT @rn := 0) AS x
    ORDER BY RAND()
) t
CROSS JOIN (SELECT COUNT(*) AS cnt FROM Orders) o
WHERE 1.0*rn / cnt <= 0.02;