I have the following two tables in my mysql database.
Table Name: groups
id group_name
1 Garments
2 Computer Accessories
3 Food
Table Name: account
id group_id account_name
1 1 T-shirt
2 1 Jeans
3 2 Motherboard
4 2 Mouse
What I am trying to display is like following:
Garments
T-Shirt
Jeans
Computer Accessories
Motherboard
Mouse
Food
I have tried the following query but could not make the output like above
SELECT group_name,accounts.account_name,accounts.id FROM `groups`
LEFT JOIN accounts ON accounts.group_id=groups.id
If I run the query it displays like following:
Garments T-Shirt
Garments Jeans
Computer Accessories Motherboard
Computer Accessories Mouse
Food NULL
Could you please show me how to display the output like I have mentioned above. Just for your information I am using Codeigniter.
Thanks a lot in advance :)
Here is the query for this purpose
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
Use group concat. This will display this result then you can explode accounts on php end
Group_name Accounts
Computer Accessories Motherboard,Mouse
Food (NULL)
Garments T-shirt,Jeans
$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;
}
}
You can place Cateogory_name and account_name into their container's and make output better .