Echo商店名称一次包含所有类别

时间:2017-05-12 10:50:19

标签: php mysql

我有3张彼此相互关联的表格。

store_manufacture -------------- 类别 ----------------- --------- Store_Categories

-----------------      --------------------          -----------------------
sm_id  | sm_name         cat_id | cat_name            sc_id|store_id|cat_id
-----------------      --------------------          -----------------------
12    | HP                 1    | Travel                1  |  12    |  1
                           2    | Health                2  |  12    |  2
                           3    | Electronics           3  |  12    |  3

我想用所有类别ID显示storename一次,我必须将其发布到下一页。这是我试过的代码:

PHP

 $cat_fetch=mysqli_query($con,"SELECT 
 sm_id,sm_brand_name,cat_id,sm_image,sm_link FROM `store_manufacture` sm 
 INNER JOIN store_category sc ON sc.store_id=sm.sm_id");
 while($row=mysqli_fetch_array($cat_fetch,MYSQLI_ASSOC){
 $id=$row['sm_id'];
 echo " <h5> <a href=''>" .$row['sm_brand_name']."   ". $row['cat_id']."</a></h5>";
 }

输出

enter image description here

所需输出

HP (Travel, Health,Electronics)

1 个答案:

答案 0 :(得分:0)

"SELECT 
 sm.sm_name,GROUP_CONCAT(c.cat_name)  as cat_name FROM `store_manufacture` sm , Categories c, Store_Categories sc
where sm.sm_id = sc.store_id AND c.cat_id = sc.cat_id GROUP BY sm.sm_id";

这是查询你应该运行希望这会帮助你