How to display datas from two different tables into one by merging datas with same id into one row?

问题: I want to display content of two table into one , one table is containing product details and another one images or the product details , Im uploading more than on image fo...

问题:

I want to display content of two table into one , one table is containing product details and another one images or the product details , Im uploading more than on image for a single product . i want o display it like, if there are 3 images for one product then three images should be displaying as same row with product details. How can i do that?

Table 1

id  pname   prodes  cat sucat   
76  bsb sbfb    fbfb    fdbfdb  
77  gripperr    black slim 7    pen ball pen    
78  technotip   black slim 7    pen ball pen    
79  gripperr    blue ink    rtnrtn  ball pen    
80  gripperr    blue ink    rtnrtn  ball pen    
82  vfdv    fdb fdbdf   bdfbdfb 

Table 2

id  pid image   
4   76  1.jpg   
5   76  2.jpg   
6   76  3.jpg   
7   77  a.jpg   
8   77  b.jpg   
9   77  c.jpg   
10  78  img_20171004_064140-1547183108.jpg  
11  78  img_20171008_110354-1547183108.jpg  
12  78  v-1547183108.jpg    
13  79  aegi-1547183474.jpg 
14  79  b-1547183474.jpg    
15  79  c-1547183474.jpg    
16  80  aegi-1547183595.jpg 
17  80  b-1547183595.jpg    
18  80  c-1547183595.jpg    
20  82  yg-1547186213.jpg   
21  82  yoongi-1547186213.jpg   

i want it like

id  pname   prodes  cat sucat   
76  bsb sbfb    fbfb    fdbfdb                    1.jpg   2.jpg  3.jpg
77  gripperr    black slim 7    pen ball pen  a.jpg   b.pjp  c.jpg  
78  technotip   black slim 7    pen ball pen    
79  gripperr    blue ink    rtnrtn  ball pen    
80  gripperr    blue ink    rtnrtn  ball pen    
82  vfdv    fdb fdbdf   bdfbdfb 

回答1:

=> try this:-

Use left join get the left table all data and the matched records from the right table.

$sql= "select P1.*, group_concat(I2.image) images
    from product P1
    left join images I2 on P1.id=I2.pid";

回答2:

You can't make different amount of columns but can join all images separated by comma with mysql function group_concat

select t1.*, group_concat(t2.image) as images
from table1 as t1
left join table2 as t2 on t1.id=t2.pid

Answer to comment

You need one more loop, something as

foreach(explode(',', $row['image'] as $url) {
   $imageURL = 'pictures/'.$url;
   echo '<img src="<?php echo $imageURL; ?>" alt="" width="100" height="100" />'
}
  • 发表于 2019-01-14 17:29
  • 阅读 ( 141 )
  • 分类:网络文章

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除