[英]Very slow execution of MySql update
我有这个SQL:
UPDATE products pr
SET pr.product_model_id = (SELECT id FROM product_models pm WHERE pm.category_id = 1 ORDER BY rand() LIMIT 1)
limit 200;
对于这200条记录,mysql服务器花费了超过15秒的时间。 表格中有220,000条记录。
这是为什么?
我有这些表是空的,但是我需要用随机信息填充它们以进行测试。
真实的估计表明我将拥有:
80类
40,000个型号
而且,大约有500,000种产品
因此,我手动创建了:
我需要它们都附上。
数据库表是:
categories {id, ...}
product_models {id, category_id, ...}
products {id, product_model_id, category_id}
尽管问题似乎有点奇怪,但是这里是对问题的快速思考。
RAND函数在大数据集上的效果不佳。
在mysql中,开发人员尝试以不同的方式实现这一目标,请查看以下文章:
我如何优化MySQL的ORDER BY RAND()函数?
http://www.titov.net/2005/09/21/do-not-use-order-by-rand-or-how-to-get-random-rows-from-table/
一种快速的方法是以下(在php中):
//get the total number of row
$result= mysql_query("SELECT count(*) as count
FROM product_models pm WHERE pm.category_id = 1 ");
$row = mysql_fetch_array($result);
$total=$row['count'];
//create random value from 1 to the total of rows
$randomvalue =rand(1,$total);
//get the random row
$result= mysql_query("UPDATE products pr
SET pr.product_model_id =
(SELECT id FROM product_models pm
WHERE pm.category_id = 1
LIMIT $randomvalue,1)
limit 200");
希望这会有所帮助。
“问题”是ORDER BY rand()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.