嵌套查询 - 有更聪明的方法

时间:2014-04-12 07:47:33

标签: mysql nested nested-queries

我有一个关于嵌套/子查询的问题,这些问题一直困扰我一段时间。

我在用PHP编写游戏。在我系统的一个非常简单的版本中,我有以下3个表:

玩家(每个玩家只有一个条目):

| player_id | player_name |

统计数据(每个玩家每场比赛都有一个条目):

| stat_id | player_id | game_id | outcome |

游戏(每个游戏都有一个条目):

| game_id | game_name |

我想查询我的数据库,并有一个表格,其结构如下所示:

| player_name | count stats for player where outcome = 1 || count stats for player where outcome = 2 |

我有以下哪些有效,但我认为有一种更聪明,更好的方法:

select a.player_name,
    (select count(*) from stats b where b.player_id = a.player_id AND b.outcome = 1) as number_of_games1,
    (select count(*) from stats b where b.player_id = a.player_id AND b.outcome = 2) as number_of_games2 
from players a

我还希望能够在外部使用“number_of_games1”或“number_of_games2”,但上述方法不允许这样做:

select a.player_name,
    (select count(*) from stats b where b.player_id = a.player_id AND b.outcome = 1) as number_of_games1,
    (select count(*) from stats b where b.player_id = a.player_id AND b.outcome = 2) as number_of_games2 
from players a where number_of_games > 5

做我想做的最聪明的方法是什么?

感谢。

1 个答案:

答案 0 :(得分:0)

您可以在条件中使用SUM()函数并使用连接,在条件中使用SUM()将得到布尔值1或0,这样您就可以计算{{1}的所需结果}和b.outcome = 1

b.outcome = 2