我需要找到一种将选择查询中的数据分组在一起的方法。因此,我输出的数据属于哪个成员属于哪个团队,但它只是将其分别推出,因此例如,在需要的三个行中,它将分别是team1 - member1team 2 - member2team1 - member3team1 - member1, member3

<?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>';

        }
    }

?>

最佳答案

一种简单的方法是先按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>';
}

10-08 04:01