1

我一直在使用 stackoverflow 来帮助我,但现在我很难过 - 希望我能在这个问题上得到一些指导:

我有两张桌子,一张包含 NFL Divisions,另一张包含 NFL Teams。它们通过 partition_id 字段(Divisions 表上的主键,Teams 表上的外键)连接。

我想做的是在查询中加入表格并按部门输出团队。我可以通过两个单独的查询/循环在 PHP 中完成此操作,但我想知道如何/是否可以通过将两个表连接到一个查询中来完成此操作。

这是我所拥有的:

$query = "SELECT Divisions.division_id, Divisions.conference, Divisions.name, 
    Teams.name FROM Divisions INNER JOIN Teams ON 
    Teams.division_id = Divisions.division_id ORDER BY Divisions.division_id";

if( $result = $db->query($query) ){
  while( $row = $result->fetch_object() ){
    // here is where I'm stuck
  }
}

我试图让最终输出看起来类似于:

AFC 北
克利夫兰布朗
匹兹堡钢人
巴尔的摩乌鸦
辛辛那提孟加拉虎

亚足联东
布法罗比尔
迈阿密海豚
等。

非常感谢任何可以帮助我的人!两年多来我没有做过任何编程,只是重新开始。

4

3 回答 3

1

循环遍历行并在division_id更改时输出新标题:

$query = "SELECT Divisions.division_id, Divisions.conference, Divisions.name, 
    Teams.name AS teamName FROM Divisions INNER JOIN Teams ON 
    Teams.division_id = Divisions.division_id ORDER BY Divisions.division_id";

if ($result = $db->query($query)) {
    $division = "";
    while ($row = $result->fetch_object()) {
        if ($division != $row["division_id"])
        {
            $division = $row["division_id"];
            echo "<br /><h2>{$row["conference"]}</h2>";
        }

        echo "{$row["teamName"]}<br />";
    }
}
于 2012-05-08T15:09:08.440 回答
0
$result = array();
if( $result = $db->query($query) ){

  while( $row = $result->fetch_object() ){
    if(empty($result[$row['division_id']])
    {
       $result[$row['division_id']] = $row;
    }
    $result[$row['division_id']]['teams'][] = $row;
  }
}
print_r($result);
于 2012-05-08T15:02:28.127 回答
0

您可以循环槽并再次检查它是否是相同的分区。如果它是一个新部门,请写下它并<br />

$query = "SELECT Divisions.division_id, Divisions.conference, Divisions.name, 
    Teams.name as teamName FROM Divisions INNER JOIN Teams ON 
    Teams.division_id = Divisions.division_id ORDER BY Divisions.division_id";

if( $result = $db->query($query) ){
    $lastDivision = -1;
  while( $row = $result->fetch_object() ){
    if($lastDivision != $row["division_id"]){
        //here it is a new division,
        echo "<b>" . $row["division_id"] . "</b><br />";
    }else{
        //not a new division so we just continu to write teams
        echo $row["teamName"] . "<br />";
    }
    $lastDivision = $row["division_id"];
  }
}
于 2012-05-08T15:04:43.523 回答