简体   繁体   中英

How to display same records all together having same product id in mysql

id    product_id    size

1     185       3
2     195       4
3     185       4
4     198       1

I want to display the of size records together having the same product id if more than one record. If it's only one product id display size as it is.

I have tried this:

$qq = mysql_query("select product_id,GROUP_CONCAT(size SEPRATOR ',')AS
size from sizes group by product_id");
while ($row = mysql_fetch_array($qq))  {
   $ad = $row['size'];
}

I am getting this error:

error:mysql_fetch_array() expects parameter 1 to be resource, 
boolean given in /home/clebster/public_html/fun.php

试试这个方法

select product_id , group_concat (`Size` separator ',') as `Size` from tablename group by product_id 
$sql="SELECT size FROM tbl WHERE id='$product_id'";
$res=mysql_query($sql);
$num_rows=myqli_num_rows($res);
if($num_rows>0)
{
for($i=0; $i<$num_rows;$i++)
{
$data=mysqli_fetch_array($res);
echo $data['size'];
}


}

Try this.

You can simply use group_concat along with group by clause as

Select product_id, group_concat(size) as size
from product_table group by product_id
order by id asc

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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