开发者

Reducing the number of queries from 2 to 1

Is it possible to use 1 query instead 2? Or this way is better? (for speed)

<?
$q1 = mysql_query("SELECT name,url,id FROM gallery") or die(mysql_error());

if (mysql_num_rows($q1) > 0) {
  while ($row = mysql_fetch_array($q1)) {   
    echo 'IMAGES FROM '.$row['name'];
    $id = $row['id'];
    //second query for each gallery
    $imgq = mysql_query("SELECT im开发者_开发问答g  FROM img WHERE ids=" . $id . " ") or die(mysql_error());
    while ($img = mysql_fetch_array($imgq)) {
      ?><img src="<?=$img['img'];?>"><?
    } //multiple images
  }
}


You need a Join to bring this back in one query.

SELECT name,url,id,img
FROM gallery g
JOIN img i ON i.ids=g.id

This is more efficient as it reduces the number of requests and table accesses you are making.

It does mean that you will be bringing back repeated rows with name,url,id but the effect of this will likely be minimal.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜