簡體   English   中英

PHP的MySQL而循環查詢優化

[英]php mysql while loop query optimization

我有運行這樣的php / mysql腳本:

$sql = "select a.column1 from table1 a";
$query = mysql_query($sql);

while ($fec = mysql_fetch_assoc($query)) {
    $sub1 = "select column1,column2 from subtable1 where id=" . $fec['a.column1'];
    $subquery1 = mysql_query($sub1);

    while ($subfec1 = mysql_fetch_assoc($subquery1)) {
        //all data .....
    }

    $sub1 = "select column1,column2 from subtable2 where id=" . $fec['a.column1'];
    $subquery2 = mysql_query($sub2);

    while ($subfec2 = mysql_fetch_assoc($subquery2)) {
        //all data .....
    }

    $sub2 = "select column1,column2 from subtable3 where id=" . $fec['a.column1'];
    $subquery3 = mysql_query($sub3);

    while ($subfec3 = mysql_fetch_assoc($subquery3)) {
        //all data .....
    }
}

現在,我在table1,subtable1,subtable2和subtable3中有許多記錄。 問題是顯示結果大約需要7個小時。 而且CPU使用率是100%

請提出優化技巧以解決此問題。

使用單個查詢獲取所有記錄

SELECT 
    a.column1,
    s.column1,
    s.column2,
    s2.column1,
    s2.column2,   
    s3.column1,
    s3.column2
FROM table1 a
LEFT JOIN subtable1 s ON s.id = a.column1
LEFT JOIN subtable2 s2 ON s.id = a.column1
LEFT JOIN subtable3 s3 ON s.id = a.column1

這里

$sql="
    SELECT 
        a.column1 acolumn1,
        s.column1 scolumn1,
        s.column2 scolumn2,
        s2.column1 s2column1,
        s2.column2 s2column2,   
        s3.column1 s3column1,
        s3.column2 s3column2
    FROM table1 a
    LEFT JOIN subtable1 s ON s.id = a.column1
    LEFT JOIN subtable2 s2 ON s.id = a.column1
    LEFT JOIN subtable3 s3 ON s.id = a.column1";
$query=mysql_query($sql);

while ($fec=mysql_fetch_assoc($query)) {
    // display any info here
}

使用別名訪問不同的表列

暫無
暫無

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

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