簡體   English   中英

PHP SQL UPDATE每行一個字段,每行數千行,每個都在PHP中構造不同

[英]PHP SQL UPDATE one field per row in thousands of rows all different each constructed in php

我有一個Large_table,其字段名為1(ID)到10和10k加行。

Update語句會導致事情變慢,導致某些記錄根本無法更新。

如果我跑

UPDATE Large_table SET SOME_FIELD = '$testdata' 

從PHP開始需要<1秒,所以WHERE子句就是問題所在。

運行

UPDATE Large_table SET SOME_FIELD = 'apple' WHERE ID ='1' 

來自它在foreach循環中的php,因此運行10k次> 30秒並超時。

我需要:1獲取所有行(如果我進行預選擇,則可以獲取單行,但是這樣的接縫就像加倍並且fetch看起來效率和快速)。 以很多行獲取所有數據我們需要其他數據中的所有數據只有一些字段,但每天都會更改。

$stmt = $conn->prepare("SELECT * FROM Large_table "); $stmt->execute(); // Works quick.

foreach ($stmt as $row){
        echo $row['1'];// works at .8 sec sometimes less
        $testdata = 'apple';

//PHP CONSTRUCT THE OUTPUT Field for each row differently depending upon id and other feilds - so for testing lets call it $testdata = 'apple' and assume it changes as the issue is not in this part

    $stmt = $conn->prepare("UPDATE Large_table SET SOME_FIELD = '$testdata' WHERE ID = '$row['1']' "); $stmt->execute();                

        }

我嘗試了CASE THEN WHEN WHEN WHEN WHEN WHEN WHEN WHEN WHEN WHEN WHEN WHEN WHEN WHEN WHEN WHEN WHOW WHOW WHO WHO

那么實現這一目標的最有效方法是什么?

嘗試准備update語句並將參數綁定到foreach之外,然后在foreach設置參數並執行語句。

$update = $conn->prepare("UPDATE Large_table SET SOME_FIELD = ? WHERE ID = ?"); 

$update->bind_param('si', $testdata, $id);

foreach ($stmt as $row)
{

  $id = $row[1];

  $testdata = 'apple'; // I'm guessing in the real code this changes per row?

  $update->execute();        

}

如果這仍然需要太長時間,那么你總是可以使用set_time_limit(0)

似乎dB表本身有一個問題,除了這個寫問題之外沒有顯示出可檢測到的錯誤。

所以

Export table as text (SQL dump)
Drop table
Restore table (with the SQL dump backup)

現在THEN WHEN方法是最快的,直到語句長度達到最大值。

下一個最快的是foreach循環之外的bind_param,由Michael(感謝)建議的版本,這是目前正在工作的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM