donglu5041 2010-12-10 03:46
浏览 61
已采纳

如何查询1对多数据库关系并正确显示行?

sorry if my question kind of doesn't make sense but i am total confused onto what im trying to accomplish.

here are my tables.

tbl_products(if the image came out small, right click on it and view picture to see it big.) alt text

tbl_product_images

alt text

basically tbl_products has the record for a product and its description. and tbl_product_images has the images for this product. i want to display the product title,description, and its images in a format like this.

alt text

problem is the query i wrote which is:

select
tbl_products.dealname,
tbl_products.desc,
tbl_products.price,
tbl_products.discount,
tbl_product_images.thumb,
tbl_product_images.large
from tbl_products
inner join tbl_product_images

on tbl_products.pHash = tbl_product_images.pHash where tbl_products.startdate = '2010-12-09';

displays the query like this.

alt text

so when i need to write something like this

while($row = mysql_fetch_assoc($query))
{
   print $row['dealname'];
   print "<img src='".$row['large']."'>";
  //and so on.
}

i will see the product displayed 4 times since i have 4 images for this product. what is the best way to perform what i am trying to accomplish? btw, phash is another way of id. its my way of relating a products identification within another table.

  • 写回答

3条回答 默认 最新

  • dongping4273 2010-12-10 17:03
    关注

    You can use the GROUP_CONCAT() function in MySQL if you want to fetch everything in one query, but you'll have to split up the image information using PHP.

    Here's an example using | (pipe) as the delimiter between thumb/large image file names.

    Query:

    select
    tbl_products.dealname,
    tbl_products.desc,
    tbl_products.price,
    tbl_products.discount,
    GROUP_CONCAT(tbl_product_images.thumb SEPARATOR '|') AS thumbs,
    GROUP_CONCAT(tbl_product_images.large SEPARATOR '|') AS images
    from tbl_products
    inner join tbl_product_images
    
    on tbl_products.pHash = tbl_product_images.pHash
    where tbl_products.startdate = '2010-12-09'
    group by tbl_products.pHash;
    

    PHP:

    while($row = mysql_fetch_assoc($query))
    {
       print $row['dealname'];
    
       // $thumbs = explode('|', $row['thumbs']);
       $images = explode('|', $row['images']);
       foreach ($images as $image) {
          print "<img src='".$image."'>";
       }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集