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!
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.
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.
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.
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>';
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With