-1

我的 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。

提前非常感谢:)

4

2 回答 2

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

使用组连接。这将显示此结果,然后您可以在 php 端展开帐户

Group_name              Accounts
Computer Accessories    Motherboard,Mouse
Food                    (NULL)
Garments                T-shirt,Jeans
于 2012-07-05T11:41:16.887 回答
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 放入他们的容器中,并使输出更好。

于 2012-07-05T11:41:34.453 回答