选择这样的东西的最快方式

时间:2014-10-23 10:41:16

标签: php mysql select while-loop

我想选择比这更快的速度,执行脚本时我的页面加载速度非常慢。

$bmw= mysqli_query($con,"SELECT * FROM cars WHERE name='bwm' 
ORDER BY date DESC LIMIT 1"); $mercedes= mysqli_query($con,"SELECT * FROM cars
WHERE name='mercedes' ORDER BY date DESC LIMIT 1"); 
$audi= mysqli_query($con,"SELECT * FROM cars WHERE name='audi'
ORDER BY date DESC LIMIT 1"); 
$skoda= mysqli_query($con,"SELECT * FROM cars WHERE name='skoda' 
ORDER BY date DESC LIMIT 1");

并在下面回复它,就像页面加载非常慢。

 while($row = mysqli_fetch_array($bmw)) { echo $row['name'] . " " .
 $row['date'];

 }

 while($row = mysqli_fetch_array($mercedes)) { echo $row['name'] . " "
 . $row['date'];

 }

 while($row = mysqli_fetch_array($audi)) { echo $row['name'] . " " .
 $row['date'];

 }

提前致谢

2 个答案:

答案 0 :(得分:0)

您编写的查询没有任何问题,您的性能问题可能是由于:

  • 缺少名称和日期的索引:在名称和日期上创建索引
  • 汽车数据库对您的硬件来说太大了:新硬件/分区/重新设计
  • 网络链接慢:Lacy K提供的解决方案很有意思,因为只有一个查询发送到mysql

您还可以通过仅选择名称和日期而不是*

来提高性能
select name, date from ...

答案 1 :(得分:0)

为什么不像这样一次选择所有制作:

$q= mysqli_query($con,"SELECT * FROM cars WHERE name IN ('bwm', 'mercedes', 'audi', 'skoda') ORDER BY date DESC LIMIT 1"); 

    while($row = mysqli_fetch_array($q)) { 
     if($row['name'] == 'bmw'){
      echo $row['name'] . " " . $row['date'];
     }
     elsif($row['name'] == 'mercedes'){
      echo $row['name'] . " " . $row['date'];
     }
     elsif($row['name'] == 'audi'){
      echo $row['name'] . " " . $row['date'];
     }
     elsif($row['name'] == 'skoda'){
      echo $row['name'] . " " . $row['date'];
     }
     else{
      echo $row['name'] . " " . $row['date'];
     }

    }