我需要找到一种方法将我的数据从我的选择查询中组合在一起。所以我输出哪些成员属于哪个团队的数据,但它只是将其全部推出,所以例如team1 - member1
,team 2 - member2
& team1 - member3
所有3行team1 - member1, member3
我需要它team2 - member 2
&amp; <?php
$sql = "
SELECT t.team_id, t.team_name, m.member_id, m.member_name
FROM teams t
LEFT JOIN team_members tm on t.team_id = tm.team_id
LEFT JOIN members m on m.member_id = tm.member_id;
";
$result = $conn->query($sql);
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
echo 'team: <strong>' . $row["team_name"] . '</strong><br>';
echo 'member: <strong>' . $row["member_name"] . '</strong><br><br>';
}
}
?>
case
答案 0 :(得分:0)
一种简单的方法是首先按team_name排序结果。
SELECT t.team_id, t.team_name, m.member_id, m.member_name
FROM teams t
LEFT JOIN team_members tm on t.team_id = tm.team_id
LEFT JOIN members m on m.member_id = tm.member_id
ORDER BY t.team_name ASC
在循环中检查团队是否与上一个团队不同。
if($result->num_rows > 0){
$LastTeam=""; $NumTeamMembers=0;
while($row = $result->fetch_assoc()){
if($LastTeam != $row["team_name"] ){
$LastTeam=$row["team_name"];
if ($NumTeamMembers>0)
echo '</strong><br><br>';
echo 'team: <strong>' . $row["team_name"] . '</strong><br>';
$NumTeamMembers=0;
}
if ($NumTeamMembers==0)
echo 'members: <strong> ';
else
echo ', ';
echo $row["member_name"];
$NumTeamMembers++;
}
echo '</strong><br><br>';
}