是否可以在此SQL语句中添加JOIN?

时间:2016-11-25 15:58:44

标签: mysql join

我有一张桌子和一个查询,用于返回得分最高的球员名单。

查询效果很好,但为了让我获取用户名,我必须根据返回的结果(player_id)执行另一个查询。

是否可以修改现有查询以加入两个表?我知道这可以通过普通查询实现,我只是不确定它是否在这个实例中,因为返回了自定义结果表。

这是我的初始表,名为results

+----------------+-------------+-----+
| Field          | Type        | Key |
+----------------+-------------+-----+
| results_id     | int         | Pri |
| community_id   | int         |     |
| player1_id     | int         |     |
| player1_goals  | int         |     |
| player2_id     | int         |     |
| player2_goals  | int         |     |
+----------------+-------------+-----+

这是我用来返回结果的查询:

select player, sum(goals) from 
((select player1_id as player, player1_goals as goals from results where community_id = 5 ) 
union all 
(select player2_id as player, player2_goals as goals from results where community_id = 5 ) 
) p 
group by player 
order by sum(goals) desc

这就是我的结果返回方式:

+----------------+------------+
| Player         | sum(goals) |
+----------------+------------+
| 2              | 94         |
| 14             | 63         |
| 7              | 43         |
+----------------+------------+

是否可以修改上述查询并在join表中添加users

+--------+-----------+
| id     | user_name  |
+---------------------+
| 2      | John       |
| 7      | Andrew     |
| 14     | Charles    |
+--------+------------+

获得输出:

+----------------+----------------+------------+
|user_name       | Player         | sum(goals) |
+----------------+----------------+------------+
| John           | 2              | 94         |
| Charles        | 14             | 63         |
| Andrew         | 7              | 43         |
+----------------+----------------+------------+

2 个答案:

答案 0 :(得分:1)

您可以使用join执行此操作。您也可以将其表达为:

select u.*,
       (select sum(case when u.id = r.player1_id then r.player1_goals else r.player2_goals)
        from results r
        where r.community_id = 5 and
              u.id in (r.player1_id, r.player2_id)
       ) as goals
from users u;

答案 1 :(得分:0)

简短回答 - 是的,你可以:

select u.user_name, sum(goals) from 
((select player1_id as player, player1_goals as goals from results where community_id = 5 ) 
union all 
(select player2_id as player, player2_goals as goals from results where community_id = 5 ) 
) p 
join users u on p.player = u.id
group by player 
order by sum(goals) desc