使用INNER JOIN创建子查询时出现问题

时间:2014-04-07 18:18:26

标签: sql join subquery

我在尝试使用INNER JOIN的子查询时遇到了麻烦。

在下面的代码中,我想要计算的平均评分只需要该玩家的平均评分<(a.player)。

通过查看下面的脚本,我的问题是

1)在使用INNER JOIN时,我应该在哪里嵌套子查询?

2)表格中有大约20个名字我从(表'学院')中提取这些信息。在子查询中,我需要'b.rating'才能成为特定的玩家。在子查询中是否需要WHERE子句,例如“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>';
}

2 个答案:

答案 0 :(得分:1)

你需要找到子查询中每个玩家的平均评分,如下所示

$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";

答案 1 :(得分:0)

$ query =&#34;选择a.player,a.team,a.loc,a.pic,a.rank ,(选择AVG(评级)FROM college_rating where player = a.player GROUP BY player)作为评级 来自大学a ORDER BY rank DESC LIMIT 20&#34 ;;