3

我有一张篮球联赛表、一张球队表和一张这样的球员表:

LEAGUES
ID   |   NAME    |
------------------
1    |   NBA     |
2    |   ABA     |

TEAMS:
ID   |   NAME    |  LEAGUE_ID
------------------------------
20   |   BULLS   |    1
21   |   KNICKS  |    2

PLAYERS:
ID   |   TEAM_ID  |  FIRST_NAME | LAST_NAME | 
---------------------------------------------
1    |      21    |   John      |  Starks   |    
2    |      21    |   Patrick   |  Ewing    |    

给定一个联赛 ID,我想从该联赛的所有球队中检索所有球员的姓名和他们的球队 ID,所以我这样做:

SELECT t.id AS team_id, p.id AS player_id, p.first_name, p.last_name
FROM teams AS t
JOIN players AS p ON p.team_id = t.id
WHERE t.league_id =  1

返回:

[0] => stdClass Object
    (
        [team_id] => 21
        [player_id] => 1
        [first_name] => John
        [last_name] => Starks
    )

[1] => stdClass Object
    (
        [team_id] => 21
        [player_id] => 2
        [first_name] => Patrick
        [last_name] => Ewing
    )

+ around 500 more objects...

由于我将使用此结果为每个团队填充包含每个团队的球员列表的下拉菜单,我想按团队 ID 对结果进行分组,因此创建这些下拉列表的循环只需循环遍历每个团队 ID 而不是每次所有 500 多名玩家。

但是当我像这样使用 GROUP BY 时:

SELECT t.id AS team_id, p.id AS player_id, p.first_name, p.last_name
FROM teams AS t
JOIN players AS p ON p.team_id = t.id
WHERE t.league_id =  1
GROUP BY t.id

它只返回每个团队的一名球员,因为使用相同的列名,会覆盖同一球队的所有其他球员。

[0] => stdClass Object
    (
        [team_id] => 21
        [player_id] => 2
        [first_name] => Patrick
        [last_name] => Ewing
    )
[1] => stdClass Object
    (
        [team_id] => 22
        [player_id] => 31
        [first_name] => Shawn
        [last_name] => Kemp
    )
etc...

我想返回这样的东西:

[0] => stdClass Object
    (
        [team_id] => 2

        [player_id1] => 1
        [first_name1] => John
        [last_name1] => Starks
        [player_id2] => 2
        [first_name2] => Patrick
        [last_name2] => Ewing

        +10 more players from this team...
    )

    +25 more teams...

有可能吗?

4

2 回答 2

4

您无法在 SQL 中执行此操作,因为您无法以数据集的形式表示该结果。你想返回复杂的对象。您可以做的是在代码中处理这个问题,并通过返回一个按 team_id 排序的数据集来帮助自己。每当您的 team_id 更改时,就该在您的代码中创建新对象并用新的玩家列表填充它。

它会是这样的(语法可能不正确):

返回结果集:

team_id|player_id|first|last
1|1|f1|l1
1|2|f2|l2
1|3|f3|l3
2|5|f5|l5
2|6|f6|l6

当这在您的代码中返回时

$lastTeamId=0;
$output=array();
foreach($results as $row){
  if($lastTeamId != $row["team_id"]){
    $lastTeamId = $row["team_id"];
    $output[$lastTeamId] = array();
  }

  $newPlayer = null;
  $newPlayer->id = $row["player_id"];
  $newPlayer->first = $row["first"];
  $newPlayer->last = $row["last"];
  $output[$lastTeamId][] = $newPlayer;
}
于 2012-10-19T14:45:57.330 回答
0

在 MySQL 中,您可以 GROUP BY team_id 然后 SELECT GROUP_CONCAT(player detail ...)。但这会受到限制,并且不是典型的关系方法。

于 2012-10-19T14:50:51.200 回答