Sql Query:2个表,但是从另一个查找一个且只有一行的所有信息

时间:2013-02-26 12:50:43

标签: php mysql sql

我有2张桌子

  • 照片:存储所有照片信息
  • 图库:存储图库的标题和说明

我需要回显一个新页面的图库描述,然后是所有应该存在的照片。

但我不断重复标题和描述,因为它在同一个

$row = mysql_fetch_array($result)...

然后我还需要那个画廊中的一组照片吗?

任何人都有帮助,或者我是模糊的......

$a="SELECT * from gallery where gallery_category=".$gallery_category;
$result = mysql_query($a,$c);
while($row = mysql_fetch_array($result)) {
    echo $row['gallery_name'].'<br>'.$row['gallery_description'].'<br>';
    $sql="SELECT * FROM photos WHERE gallery_id =".$gallery_id." ORDER BY photos_filename";
    $result2 = mysql_query($sql,$c);
    while($row = mysql_fetch_array($result2)) {
        echo'<a rel="example_group" href="../galleries/images/'.$row['gallery_id'].'/'.$row['photos_filename'].'" width="130" height="100"><img src="../galleries/images/'.$row['gallery_id'].'/'.$row['photos_filename'].'" height="150px" alt=""/></a>';
    }
}

1 个答案:

答案 0 :(得分:0)

其实我会在这里发布,所以我可以使用一些代码格式化。

选项1 - 循环内循环

$headerquery = $db->query("SELECT * FROM tbl1");
while ($headers= $db->fetchNextObject($headerquery )) {
   echo "<table><tr><th>".$headers->GalleryName."</th></tr>"; // open table create header
       $detailquery = $db->query("SELECT * FROM tbl2 WHERE GalleryID=".$headers->ID);
       while ($details= $db->fetchNextObject($detailquery )) {
          echo "<tr><td>".$details->Photo."</td></tr>"; //loop through 2nd table and spit out photos
       }
   echo "</table>"; //close table
}

选项2 - 使用选择器加入查询

$galleryheaderid = 0;
$query = $db->query("SELECT * FROM tbl1 INNER JOIN tbl2 on tbl1.ID=tbl2.GalleryID");
while ($details = $db->fetchNextObject($query )) {
   echo "<table>";
   if ($galleryheaderid!=$details->ID) { //spit out header row if id's don't match
       echo "<tr><th>".$details ->GalleryName."</th></tr>"; //create header
       $galleryheaderid = $details->ID;  //set header id to gallery id so we don't show header a 2nd time
   } 
   echo "<tr><td>".$details->Photo."</td></tr>"; //spit out gallery information even on first row since all rows include photo information

   echo "</table>"; //close table
}

其中任何一个都应该显然可以正常工作