Sql查询:2个表,但从其中一行查找所有信息,而从另一行只查找一行


Sql Query: 2 tables but looking for all information from one and only one row from the other

我有两个表

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

我需要回显到一个新的页面画廊描述,然后所有的照片应该在那里。

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

$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-循环内循环

$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
}

这两种方法中的任何一种都应该有效,显然它们需要正确完成