Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I group rows with the same value from mySQL into php?

Tags:

php

mysql

This is my mySQL table animals:

    ╔══════════╦══════╗
    ║  animal  ║ name ║
    ╠══════════╬══════╣
    ║   dog    ║ sam  ║
    ║   cat    ║ fred ║
    ║   cat    ║ todd ║
    ║  bird    ║ alan ║
    ╚══════════╩══════╝

I want to select all data into a table:

            $sql = 'SELECT  *  FROM animals';
            foreach ($pdo->query($sql) as $row) {
                echo '<td>'.$row['animal'].' </td>';
                echo '<td>'.$row['name'].' </td>';
            }

My result is:

    ╔══════════╦══════╗
    ║   dog    ║ sam  ║
    ║   cat    ║ fred ║
    ║   cat    ║ todd ║
    ║  bird    ║ alan ║
    ╚══════════╩══════╝

But I want to output rows with the same animal only once, but with all the names in one row, like this:

    ╔══════════╦═════════════╗
    ║   dog    ║ sam         ║
    ║   cat    ║ fred, todd  ║
    ║  bird    ║ alan        ║
    ╚══════════╩═════════════╝

I have no idea how to achieve this. I try to think in this direction:

SELECT  *  FROM animals GROUP BY animal

But I am stuck! I am happy for every hint!

like image 580
peace_love Avatar asked Jun 21 '16 12:06

peace_love


People also ask

How do I group the same values in SQL?

The SQL GROUP BY Statement The GROUP BY statement groups rows that have the same values into summary rows, like "find the number of customers in each country". The GROUP BY statement is often used with aggregate functions ( COUNT() , MAX() , MIN() , SUM() , AVG() ) to group the result-set by one or more columns.

Which group is used to put the same value in all the rows?

Summary. The GROUP BY Clause SQL is used to group rows with same values. The GROUP BY Clause is used together with the SQL SELECT statement.


3 Answers

MySQL has a non-standard SQL function called GROUP_CONCAT specifically to do this.

Use as:

SELECT  animal, GROUP_CONCAT(name) as grouped_name  FROM animals GROUP BY animal

Use in PHP:

 $sql = ' SELECT  animal, GROUP_CONCAT(name) as grouped_name  FROM animals GROUP BY animal';
 foreach ($pdo->query($sql) as $row) {
     echo '<td>'.$row['animal'].' </td>';
     echo '<td>'.$row['grouped_name'].' </td>'; 
 }

Note how the column with the group is renamed/aliased to grouped_name this is because that column is not the name column anymore. You can refer to this column by its alias grouped_name in your sql result.

like image 197
apokryfos Avatar answered Oct 11 '22 04:10

apokryfos


SELECT  
  a.animal
  GROUP_CONCAT(a.name) names
FROM animals a
GROUP BY a.animal

Note check my changed query and change your php fragment $row['name'] to $row['names']

Update change your loop to:

        foreach ($pdo->query($sql) as $row) {
            echo '<tr><td>'.$row['animal'].' </td>';
            echo '<td>'.$row['names'].' </td></tr>';
        }
like image 45
Alex Avatar answered Oct 11 '22 05:10

Alex


You can acheive it using GROUP BY AND GROUP_CONCAT.

GROUP BY is used in conjunction with aggregate functions to group the result by one or more columns.

GROUP_CONCAT is a aggregate function used to concatenate the columns which is being grouped.


So in your case you should GROUP BY animal column and apply GROUP_CONCAT on the same. Like this:

SELECT  
  A.animal
  GROUP_CONCAT(A.name)
FROM animals A
GROUP BY A.animal
like image 21
Alok Patel Avatar answered Oct 11 '22 03:10

Alok Patel