MySQL:如何更新随机选择的 50% 的行?

标签 mysql random percentage

我想更新表中随机选择的 50% 的行。有什么办法吗?

编辑:只是为了澄清它应该始终更新 50% 的记录,但是必须随机选择这 50% 的行(例如不仅是前 50%)。换句话说,平均而言,每隔一条记录都应该更新。

最佳答案

应该像这样工作:

UPDATE table SET x = y WHERE RAND() < 0.5

是的,经过测试,有效。但当然,平均只有 50% 的行,而不是恰好 50%。

如 SQL 92 规范中所写,WHERE必须为每个元组执行子句,因此 rand()必须重新评估以产生预期结果(而不是选择所有行或根本不选择行)。

规范摘录(强调我的):

General Rules

1) The <search condition> is applied to each row of T. The result of the <where clause> is a table of those rows of T for which the result of the <search condition> is true.

2) Each <subquery> in the <search condition> is effectively executed for each row of T and the results used in the application of the <search condition> to the given row of T. If any executed <subquery> contains an outer reference to a column of T, then the reference is to the value of that column in the given row of T.

关于MySQL:如何更新随机选择的 50% 的行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11087059/

相关文章:

php - 需要循环逻辑帮助 - 无法正确比较

php - 使用 AJAX/jQuery 在文本区域中显示 PHP 回显?

Java线程安全的数据库连接

java - 将整数映射为百分比 [0,100]

mysql - 使用子查询计算两个表的百分比

python - 在python中使用MySQLdb向数据库插入新元素时发生内存泄漏

r - 如何从R中的矩阵中重复选择行样本?

python - Python 设置的无序可以被认为是随机顺序吗?

swift 2.0 分配了哪个图像

Android:按百分比排名?