我有下表,其中存储了每个车手和他所竞争的车队的得分。
driver team points
-------------------------
Josh Mercedes 12
Aron BMW 5
Ben Mercedes 9
Jake BMW 17
Mike BMW 7
Brad Chevrolet 3
现在我想显示每个团队的得分+团队中所有车手的名字。
所需的输出:
BMW 29 Aron, Jake, Mike
Mercedes 21 Josh, Ben
Chevrolet 3 Brad
查询: 我的查询的问题是它只显示第一个驱动程序的名称。我必须使用什么功能来包含所有驱动程序的名称?
<?php
$sql = "SELECT driver, team, points, SUM(points) AS totals FROM `example-table` GROUP BY team ORDER BY `points` DESC";
$stmt = $pdo->prepare($sql);
$stmt->execute();
if($stmt->rowCount())
{
while ($result = $stmt->fetch(PDO::FETCH_ASSOC))
{
echo $result['team'];
echo $result['driver'];
echo $result['totals'];
?>
<br>
<?php
}// end while
}// end if
else {
echo '0 results';
}// end else
?>
答案 0 :(得分:3)
使用Group_Concat功能
SELECT team, SUM(points) AS totals,group_concat(driver)
FROM `example-table`
GROUP BY team
ORDER BY `points` DESC