简体   繁体   English

将查询数量从2减少到1

[英]Reducing the number of queries from 2 to 1

Is it possible to use 1 query instead 2? 是否可以使用1个查询而不是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 img  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. 您需要一个Join才能将其重新置于一个查询中。

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. 它确实意味着你将带回name,url,id重复行name,url,id但这种效果可能很小。

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

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