提高SELECT查询速度?

use*_*378 1 php mysql

在浏览器上显示数据需要40秒,这是不可接受的.

下面的代码,它显示了category.takeawayID = xxxxx中的所有内容以及项目和选项表中的循环.

类别表:总计超过15,000行

items表:超过100,000行

item_options表:超过150,000行.

如何提高性能?

 $qcat = mysql_query("select * from categories where takeawayID=55276");
 while($c_row = mysql_fetch_assoc($qcat)) 
 {
     echo "<h2>" . $c_row['name'] . "</h2>";
     echo "<div>" . $c_row['description'] . "</div><br /> <br />";

     $qitem = mysql_query("select * from items where category_id =". $c_row['id']);

      while($i_row = mysql_fetch_assoc($qitem)) {
           echo "<div style='backround-color:pink'>" . $i_row['name'] . "</div>";

           $qoption = mysql_query("select * from item_options where item_id =". $i_row['id']);

           while($o_row = mysql_fetch_assoc($qoption)) {
               echo " (" . $o_row['price'] . ") ";
           }
      }
 }
Run Code Online (Sandbox Code Playgroud)

最大记录显示200到500行,具体取决于takeawayID ID

Sha*_*ngh 5

您可以尝试使用连接创建单个查询,并确保已在列上创建索引.

select * from categories c 
left join items t
on c.id= t.category_id
left join item_options io 
on t.id=io.item_id
Where c.takeawayID=55276
Run Code Online (Sandbox Code Playgroud)

  • @ user622378:当然,你必须编写逻辑来显示数据,如果你保持这3级嵌套循环它总是需要时间 (2认同)