简体   繁体   English

PHP的MySQL而循环查询优化

[英]php mysql while loop query optimization

I have php/mysql script running which is like this: 我有运行这样的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 .....
    }
}

Now I've many many many records in table1, subtable1, subtable2 and subtable3. 现在,我在table1,subtable1,subtable2和subtable3中有许多记录。 And problem is that it takes around 7 hours to display the results. 问题是显示结果大约需要7个小时。 Moreover the CPU Usage is 100% 而且CPU使用率是100%

Please suggest the optimization tips to overcome this issue. 请提出优化技巧以解决此问题。

Use a single query to get all records 使用单个查询获取所有记录

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

Here 这里

$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
}

Use aliases for accessing different table columns 使用别名访问不同的表列

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM