Question

I'm having trouble trying to use a subquery with an INNER JOIN.

In the code below, the average rating I'm trying to compute needs to be only the average rating of that player (a.player).

From looking at my script below, my questions are:

1) Where should I nest the subquery when using INNER JOIN?

2) There are about 20 names in the table I'm pulling this information from (table 'college'). In the subquery I need 'b.rating' to be for that specific player. Do I need a WHERE clause in the subquery, something like "WHERE player=a.player"?

$query = "SELECT a.player,a.team,a.loc,a.pic,a.rank,b.rating FROM college AS a
        JOIN (SELECT AVG(rating) AS rating FROM college_rating) AS b
        ON a.player=b.player
        ORDER BY rank DESC LIMIT 20";
$run = mysqli_query($link,$query);
while($row = mysqli_fetch_array($run)) {
echo $row['player'] . ' ' . $row['rating'] . ' ' . $row['team'] . '<br>';
}
Was it helpful?

Solution

You need to find average rating for each palyer in subquery as shown below

$query = "SELECT a.player,a.team,a.loc,a.pic,a.rank,b.rating FROM college AS a
          JOIN (
                SELECT player,AVG(rating) AS rating 
                FROM college_rating
                GROUP BY player
               ) AS b
        ON a.player=b.player
        ORDER BY rank DESC LIMIT 20";

OTHER TIPS

$query = "SELECT a.player,a.team,a.loc,a.pic,a.rank , ( SELECT AVG(rating) FROM college_rating where player = a.player GROUP BY player ) as rating FROM college a ORDER BY rank DESC LIMIT 20";

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top