将mysql值显示为类别和项目

时间:2012-07-05 11:35:19

标签: php mysql codeigniter

我的mysql数据库中有以下两个表。

表名:组

 id    group_name
 1     Garments
 2     Computer Accessories 
 3     Food

表名:帐号

 id     group_id    account_name
 1         1        T-shirt
 2         1        Jeans
 3         2        Motherboard
 4         2        Mouse

我想要显示的内容如下:

Garments 
      T-Shirt
       Jeans
Computer Accessories
       Motherboard
       Mouse
Food

我尝试了以下查询,但无法像上面那样进行输出

 SELECT group_name,accounts.account_name,accounts.id FROM `groups`
 LEFT JOIN accounts ON accounts.group_id=groups.id 

如果我运行查询,则显示如下:

  Garments                T-Shirt
  Garments                Jeans
  Computer Accessories    Motherboard
  Computer Accessories    Mouse
  Food                    NULL

请您告诉我如何显示输出,就像我上面提到的那样。仅供参考,我使用的是Codeigniter。

提前多多感谢:)

2 个答案:

答案 0 :(得分:1)

以下是此目的的查询

select
  group_name as Group_name,
  group_concat(account_name) as Accounts
from garments
  left join account
    on account.group_id = garments.id
group by garments.group_name

使用group concat。这将显示此结果,然后您可以在php端爆炸帐户

Group_name              Accounts
Computer Accessories    Motherboard,Mouse
Food                    (NULL)
Garments                T-shirt,Jeans

答案 1 :(得分:0)

$categories = mysql_query('select * from groups');
while($category = mysql_fetch_array($categories))
{
   $ID = $category['id'];
   $category_name = $category['group_name'];
   echo $category_name;

   $accounts = mysql_query("select * from account where group_id = $ID");
   while($account = mysql_fetch_array($accounts))
   {
      $account_name = $account['account_name'];
      echo 'TAB TAB TAB '.$account_name;
   }
}

您可以将Cateogory_name和account_name放入其容器中,并使输出更好。