-1

I have a table in MySQL which has group_id and name columns (the table has multiple users divided into groups using group_id).

table design and data

I want to display these users in the html table using grouping of names.

grouping of names

I used the following MySQL query, but it does not do the job.

SELECT 
    * 
FROM `teams` 
WHERE 1
GROUP BY 
    group_id

What should I do to get the output using PHP and MySQL?

veljasije
  • 6,722
  • 12
  • 48
  • 79
Francis
  • 147
  • 3
  • 15
  • Here is the Possible [Duplicate](http://stackoverflow.com/questions/12668528/sql-server-group-by-clause-to-get-comma-separated-values) of your question. – Manjeet Barnala Apr 14 '16 at 07:10

4 Answers4

0

You should use group_concat for the query

SELECT group_id, GROUP_CONCAT(name)
from teams 
group by group_id;
ScaisEdge
  • 131,976
  • 10
  • 91
  • 107
0

Use GROUP_CONCAT() function for that:

SELECT
    group_id,
    GROUP_CONCAT(`name`) AS teams
FROM
    teams
GROUP BY
    group_id
mitkosoft
  • 5,262
  • 1
  • 13
  • 31
0

Try below SQL query

select 
id,group_concat(concat(`name`) separator ',')
as Result from teams group by group_id
Ajay
  • 235
  • 2
  • 8
0

When using GROUP_CONCAT(name) in the examples above and you get your query back you can do the following in php to loop through the results.

SELECT group_id, group_concat(name) AS team FROM your_table GROUP BY group_id

$html = [];
foreach ($results as $row) {
    $html []= "<div>";
        $html []= "GROUP ID:" . $row['group_id'];
        $html []= "TEAM:" . $row['team'];
    $html []= "</div>";
}
echo join("", $html);

Note: I am using a $html array here because cause its more memory efficient to use an array for large scale string concatenations than it is to use .= string operator.