Note that there are some explanatory texts on larger screens.

plurals
  1. POSQL: GROUP BY after JOIN without overriding rows?
    primarykey
    data
    text
    <p>I have a table of basketball leagues, a table af teams and a table of players like this:</p> <pre><code>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 | </code></pre> <p>Given a League ID, I would like to retrieve all the players' names and their team ID from all the teams in that league, so I do this:</p> <pre><code>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 </code></pre> <p>which returns:</p> <pre><code>[0] =&gt; stdClass Object ( [team_id] =&gt; 21 [player_id] =&gt; 1 [first_name] =&gt; John [last_name] =&gt; Starks ) [1] =&gt; stdClass Object ( [team_id] =&gt; 21 [player_id] =&gt; 2 [first_name] =&gt; Patrick [last_name] =&gt; Ewing ) + around 500 more objects... </code></pre> <p>Since I will use this result to populate a dropdown menu for each team containing each team's list of players, I would like to group my result by team ID, so the loop to create these dropdowns will only have to cycle through each team ID instead of all 500+ players each time. </p> <p>But when I use the GROUP BY like this:</p> <pre><code>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 </code></pre> <p>it only returns one player from each team like this, overriding all the other players on the same team because of the use of the same column names. </p> <pre><code>[0] =&gt; stdClass Object ( [team_id] =&gt; 21 [player_id] =&gt; 2 [first_name] =&gt; Patrick [last_name] =&gt; Ewing ) [1] =&gt; stdClass Object ( [team_id] =&gt; 22 [player_id] =&gt; 31 [first_name] =&gt; Shawn [last_name] =&gt; Kemp ) etc... </code></pre> <p>I would like to return something like this:</p> <pre><code>[0] =&gt; stdClass Object ( [team_id] =&gt; 2 [player_id1] =&gt; 1 [first_name1] =&gt; John [last_name1] =&gt; Starks [player_id2] =&gt; 2 [first_name2] =&gt; Patrick [last_name2] =&gt; Ewing +10 more players from this team... ) +25 more teams... </code></pre> <p>Is it possible somehow?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload