嵌套的mysql查询到单个查询中

时间:2012-10-03 07:30:45

标签: mysql nested-queries

$image=mysql_query("select * from carad order by carAdID DESC LIMIT 10");

    while($row=mysql_fetch_array($image))
    {
          $getimage=mysql_query("select * from carimage where carAdID='".$row["carAdID"]."' LIMIT 1");
          while($getimagerow=mysql_fetch_array($getimage))
          {
              echo(''); 
              echo('<a href="#" ><div class="simages"><img src="'.substr($getimagerow["carImageUrl"],1).'" width="600" height="400" /><div class="SliderContent">'.$row["catalogPrice"].'</div></div></a>');
          }
    }

我正在使用两个查询,一个是在循环之前,在while循环中,id来自第一个查询是否有任何最好的方法在单个查询中调用这些查询,因此它将进行优化。

1 个答案:

答案 0 :(得分:0)

试试这个:

SELECT ci.*
FROM carimage ci 
INNER JOIN 
(
    select * 
    from carad 
    order by carAdID DESC LIMIT 10
 ) c ON ci.carAdID = c.carAdID
 --May be you need to add LIMIT here as well