[英]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.