[英]How can I group rows with the same value from mySQL into php?
This is my mySQL table animals
: 这是我的mySQL表
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!
我很高兴每一个提示!
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']
注意检查我更改的查询并将您的php片段
$row['name']
更改$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>';
}
MySQL has a non-standard SQL function called GROUP_CONCAT
specifically to do this. MySQL有一个非标准的SQL函数,名为
GROUP_CONCAT
专门用于执行此操作。
Use as: 用于:
SELECT animal, GROUP_CONCAT(name) as grouped_name FROM animals GROUP BY animal
Use in PHP: 在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. 请注意如何将具有组的列重命名/别名为
grouped_name
这是因为该列不再是name
列。 You can refer to this column by its alias grouped_name
in your sql result. 您可以在sql结果中通过别名
grouped_name
来引用此列。
You can acheive it using GROUP BY AND GROUP_CONCAT . 您可以使用GROUP BY和GROUP_CONCAT来实现它 。
GROUP BY is used in conjunction with aggregate functions to group the result by one or more columns. GROUP BY与聚合函数结合使用,将结果分组为一列或多列。
GROUP_CONCAT is a aggregate function used to concatenate the columns which is being grouped. GROUP_CONCAT是一个聚合函数,用于连接正在分组的列。
So in your case you should GROUP BY animal
column and apply GROUP_CONCAT on the same. 因此,在您的情况下,您应该GROUP BY
animal
列并在同一个上应用GROUP_CONCAT 。 Like this: 像这样:
SELECT
A.animal
GROUP_CONCAT(A.name)
FROM animals A
GROUP BY A.animal
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.