简体   繁体   English

SQL查询:2个表,但从一个表中查找所有信息,而从另一表中仅查找一行

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

I have 2 tables 我有2张桌子

  • Photos: stores all photo information 照片:存储所有照片信息
  • Gallery: stores heading and description about the gallery 画廊:商店的标题和描述

I need to echo to a new page the Gallery Description, then all the photos that should be there. 我需要回显图库描述的新页面,然后显示所有应该存在的照片。

but I keep getting heading and description repeating because its in the same 但我一直在重复标题和说明,因为它们在同一位置

$row = mysql_fetch_array($result)...

then there is more that one set of photos in that gallery I need also? 那我画廊还需要多张照片呢?

anyone help or am I being to vague.... 任何人的帮助或我正在模糊...

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

Actually I'll post it up here so I can use some code formatting. 实际上,我将其张贴在这里,以便可以使用一些代码格式。

Option 1 - loop within a loop 选项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
}

Option 2 - joined query with selector 选项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
}

Something like either of these should work obviously they'll need completing properly 这些东西中的任何一个显然应该起作用,他们需要正确完成

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

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