php mysql while循环查询优化

时间:2014-09-01 07:18:27

标签: php mysql

我运行了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%

请建议优化提示以解决此问题。

1 个答案:

答案 0 :(得分:1)

使用单个查询获取所有记录

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
}

使用别名访问不同的表列